Reputation: 6169
I have been pulling my hair out figuring out how to get an image from my App Engine bucket (or any private bucket) and display it on my Flask website running on GCP's App Engine.
I'm trying variations of the following:
@app.route('/get_object/<object>')
def get_object(object):
client = storage.Client()
bucket = client.get_bucket('bucket-id')
blob = bucket.get_blob(object)
return blob
and my HTML looks like so:
<img src={{ url_for('get_object', object='test.jpg') }}>
And in my App Engine default bucket I have there sitting a photo called test.jpg
, but nothing seems to work. My bucket must be private, is there anyway to serve private files?
Upvotes: 0
Views: 1269
Reputation: 6169
I did this:
My image src uses a python function to pass the bucket and object
<img src="{{ url_for('get_file', bucket='testBucket', object='image.png') }}">
here's the function
@app.route('/get_file/<testBucket>/<object>')
@requires_auth
def get_file(testBucket, object):
storage_client = storage.Client()
bucket = storage_client.get_bucket(testBucket)
blob = bucket.blob(object)
with tempfile.TemporaryDirectory() as tmpdirname:
fullpath = os.path.join(tmpdirname, object)
blob.download_to_filename(fullpath)
return send_from_directory(tmpdirname, object)
This saves the files local to the App Engine application in a temporary directory that gets deleted once the function exists on the return, so the user gets the file but the temp location no longer exists. I think...
Upvotes: 1