Write to Google Cloud Storage from Cloud Function (python)

David Ferris picture David Ferris · Sep 10, 2018 · Viewed 8k times · Source

I am trying to upload a file to google cloud storage from within a cloud function. I can't import the cloud storage library into my function, though.

Can cloud storage be used from within cloud functions in this manner?

Cloud Function

from google.cloud import storage

def upload_blob(bucket_name, blob_text, destination_blob_name):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_string(blob_text)

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))

def log_data(request):
    request_json = request.get_json()
    BUCKET_NAME = 'my-bucket'
    BLOB_NAME = 'test-blob'
    BLOB_STR = '{"blob": "some json"}'

    upload_blob(BUCKET_NAME, BLOB_STR, BLOB_NAME)
    return f'Success!'

Error

Deployment failure:
Function load error: Code in file main.py can't be loaded.
  File "/user_code/main.py", line 1, in <module>
    from google.cloud import storage
ImportError: cannot import name 'storage' from 'google.cloud' (unknown location)

Answer

Dustin Ingram picture Dustin Ingram · Sep 10, 2018

You need to add the google-cloud-storage package to your requirements.txt file to install it in the Cloud Functions environment.