【发布时间】:2020-06-27 11:47:19
【问题描述】:
我需要将 Python 生成的图像上传到 Azure Blob 存储,而不是在本地保存。 此时我生成了一张图片,将其保存在本地并上传到存储中(参见下面的代码),但我需要为大量图像运行它并且不需要它依赖于本地存储。
我尝试以流的形式(特别是字节流)保存它,因为上传似乎也在使用流(对不起,如果这是一种天真的方法,我在 Python 方面没有那么经验)但我不知道如何在上传过程中使用它。如果我像打开本地文件一样使用它,它会上传一个空文件。
我使用的是 azure-storage-blob 版本 12.2.0。我注意到在以前版本的 azure-storage-blob 中,可以从流中上传(特别是 BlockBlobService.get_blob_to_stream),但我在这个版本中找不到它,并且由于某些依赖关系,我无法降级包。
非常感谢任何帮助。
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
from azure.storage.blob import ContainerClient
# create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.sin(2 * np.pi * t)
# plot it
fig, ax1 = plt.subplots()
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp')
ax1.plot(t, data1)
# save it locally
plt.savefig("example.png")
# create a blob client and upload the file
container_client = ContainerClient.from_container_url(container_SASconnection_string)
blob_client = container_client.get_blob_client(blob = "example.png")
with open("example.png") as data:
blob_client.upload_blob(data, blob_type="BlockBlob")
# ALTERNATIVELY, instead of saving locally save it as an image stream
fig, ax1 = plt.subplots()
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp')
ax1.plot(t, data1)
image_stream = BytesIO()
plt.savefig(image_stream)
# but this does not work (it uploads an empty file)
# blob_client.upload_blob(image_stream, blob_type="BlockBlob")
【问题讨论】: