2
votes

How do you open a file (from App Engine) that's stored in Google Cloud Storage?

I am using Python, Flask and App Engine (Flexible environment). The file is not public, the bucket belongs to the App Engine project, so has the correct permissions set.

app.yaml

runtime: python
env: flex
entrypoint: gunicorn -b :$PORT view:app
runtime_config:
  python_version: 3.5
env_variables:
    CLOUD_STORAGE_BUCKET: <project-xxxx>

view.py

...
from google.cloud import storage 
gcs = storage.Client()

@app.route('/start_serving/<file_name>')
def start(file_name):
    WHAT TO DO HERE?

#Rest of the app

Thank you in advance. I couldn't find anything related in documentation. It provides information on how to create a bucket, how to upload, how to download, how to give permission, but nothing about how to read it.

Also, how can I open it from my computer (before running the 'gcloud app deploy' command)?

1

1 Answers

3
votes

I have a python2.7 flex app, where I upload to GCS using blob.upload_from_string() but it looks like there is a blob.download_as_string() so maybe something like this would work

from google.cloud import storage

project_id = os.environ['GCLOUD_PROJECT']
CLOUD_STORAGE_BUCKET = "%s.appspot.com" % project_id

@app.route('/start_serving/<file_name>')
def start(file_name):
    gcs = storage.Client()
    bucket = gcs.get_bucket(CLOUD_STORAGE_BUCKET)
    blob = bucket.blob(file_name)
    return blob.download_as_string()