我有一个用于数据处理的Python代码,我想使用azure block blob作为代码的数据输入,具体来说,是来自 block blob的csv文件。将 csv 文件从 azure blob 下载到本地路径,如果在本地运行,则以其他方式上传 python 代码,这一切都很好,但问题是我的代码在 azure 虚拟机上运行,因为它对于我的 Apple Air 来说相当重,pandas read_csv在这种情况下,从本地路径不起作用,因此我必须通过流下载、上传和更新 csv 文件到 azure 存储,而不进行本地保存。下载和上传 csv 的体积都非常小,远小于 blob block 限制
没有太多教程来解释如何一步一步执行此操作,MS Docs 通常也很难解释,我的最小代码如下:
用于从 azure blob 存储下载
from azure.storage.blob import BlockBlobService
storage = BlockBlobService(account_name='myname', account_key = 'mykey')
#here i don't know how to make a csv stream that could could be used in next steps#
file = storage.get_blob_to_stream('accountname','blobname','stream')
df = pd.read_csv(file)
#df for later steps#
用于通过数据帧从代码按流上传和更新 blob
df #dataframe generated by code
'i don't know how to do the preparation steps for df and the final fire up operation'
storage.put_blob_to_list _by_stream('accountname','blobname','stream')
你能给我做一个逐步的教程吗,对于有azure blob经验的人来说,这应该不是很困难。
或者,如果您除了在我的情况下使用 blob 之外还有更好的解决方案,请点击一些。谢谢。
最佳答案
所以文档还在进行中,我认为它越来越好...... 有用的链接:
- Github - Microsoft Azure Storage SDK for Python
- Quickstart: Upload, download, and list blobs using Python
要从 Blob 存储中以流的形式下载文件,您可以使用 BytesIO
:
from azure.storage.blob import BlockBlobService
from io import BytesIO
from shutil import copyfileobj
with BytesIO() as input_blob:
with BytesIO() as output_blob:
block_blob_service = BlockBlobService(account_name='my_account_name', account_key='my_account_key')
# Download as a stream
block_blob_service.get_blob_to_stream('mycontainer', 'myinputfilename', input_blob)
# Do whatever you want to do - here I am just copying the input stream to the output stream
copyfileobj(input_blob, output_blob)
...
# Create the a new blob
block_blob_service.create_blob_from_stream('mycontainer', 'myoutputfilename', output_blob)
# Or update the same blob
block_blob_service.create_blob_from_stream('mycontainer', 'myinputfilename', output_blob)
关于Python 脚本按流使用 Azure 存储 Blob 中的数据,并按流更新 Blob,无需本地文件读取和上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49467961/