从flask python将matplotlib输出图上传到云存储

时间:2018-06-27 05:02:06

标签: python matplotlib flask

我正在灵活的应用程序引擎环境中使用Python运行烧瓶应用。我想将matplotlib输出图像直接上传到Google云存储桶。有什么办法吗?下面是我的代码。我应该怎么做?

x = data
# the histogram of the data
n, bins, patches = plt.hist(x, 25, normed=1, facecolor='green', alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=1)

plt.xlabel('X-Axis')
plt.ylabel('Probability')
plt.title(r'Histogram ')
plt.grid(True)
plt.savefig('2.png')

那么,在有/没有“ plt.savefig('2.png')”之后,有什么方法可以将直方图上传到云存储中吗?谢谢。 :)

1 个答案:

答案 0 :(得分:2)

首先,您需要通过pip install google-cloud-storage安装适用于Python的Google云存储客户端。然后将其导入您的代码。

然后,您可以创建一个缓冲区,在其中将缓冲区临时存储Matplotlib的savefig方法的输出,然后再通过upload_from_string上的blob方法将该缓冲区上载到Google云存储。

以下是使用您的代码的完整示例:

import io
from google.cloud import storage

client = storage.Client(project='your-gcp-project-id')
bucket = client.bucket('your-gcs-bucket-name')
blob = bucket.blob('your-filename.png')

x = data
# the histogram of the data
n, bins, patches = plt.hist(x, 25, normed=1, facecolor='green', alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=1)

plt.xlabel('X-Axis')
plt.ylabel('Probability')
plt.title(r'Histogram ')
plt.grid(True)

# temporarily save image to buffer
buf = io.BytesIO()
plt.savefig(buf, format='png')

# upload buffer contents to gcs
blob.upload_from_string(
    buf.getvalue(),
    content_type='image/png')

buf.close()

# gcs url to uploaded matplotlib image
url = blob.public_url