使用 pickle 或 dill 从 Azure blob 存储读取文件,而不保存到磁盘

Sam*_*uel 3 pickle dill azure-blob-storage azure-functions

我正在尝试从 Python 中的 Azure 存储 Blob 读取机器学习模型的权重。这应该在 Azure Functions 中运行,所以我不相信我能够使用将 blob 保存到磁盘的方法。

我使用的是 azure-storage-blob 12.5.0,而不是旧版本。

我尝试使用Dill.loads加载 .pkl 文件,如下所示:

connection_string = 'my_connection_string'
blob_client = BlobClient.from_connection_string(connection_string, container_name, blob_name)
downloader = blob_client.download_blob(0)

with BytesIO() as f:
    downloader.readinto(f)
    weights = dill.loads(f)
Run Code Online (Sandbox Code Playgroud)

返回:

>>> TypeError: a bytes-like object is required, not '_io.BytesIO'
Run Code Online (Sandbox Code Playgroud)

我不确定使用 Pickle 的方法会如何。怎么解决这个问题呢?

Sam*_*uel 8

以下是这个问题的解决方法:

def get_weights_blob(blob_name):
    connection_string = 'my_connection_string'
    blob_client = BlobClient.from_connection_string(connection_string, container_name, blob_name)
    downloader = blob_client.download_blob(0)

    # Load to pickle
    b = downloader.readall()
    weights = pickle.loads(b)

    return weights
Run Code Online (Sandbox Code Playgroud)

然后使用以下函数检索权重:

weights = get_weights_blob(blob_name = 'myPickleFile')
Run Code Online (Sandbox Code Playgroud)