upload matplotlib output plot to cloud storage from flask python

1.3k views Asked by At

I am running a flask app in Python in flexible app engine environment. I want to upload the matplotlib output image directly to a google cloud bucket. Is there any way to do this? Below is my code. How should I proceed further?

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')

so is there any way i can upload the histogram to cloud storage after/without "plt.savefig('2.png')" ? Thanks. :)

1

There are 1 answers

0
Orphem On

First of all, you need to install google cloud storage client for Python via pip install google-cloud-storage. Then import it into your code.

You can then create a buffer where you would temporarily store the output of Matplotlib's savefig method before uploading this buffer to google cloud storage through the upload_from_string method on blob.

Here is a complete example using your code:

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