35

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)
David Ferris
  • 2,215
  • 6
  • 28
  • 53
  • 2
    Did you add google.cloud (google-cloud-storage) to your requirements? https://cloud.google.com/functions/docs/concepts/python-runtime#specifying_dependencies – Doug Stevenson Sep 10 '18 at 01:36
  • 1
    Sorry but how do you test this sort of parameterised functions in Cloud Functions ? – Prany Dec 03 '20 at 23:58

1 Answers1

39

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

Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
  • thanks for the answer it did solve my problem too but how do you test this sort of multi parameterised functions in Cloud Functions – Prany Dec 04 '20 at 11:46
  • 1
    I'm not sure what you mean, can you ask a new question with more details? – Dustin Ingram Dec 04 '20 at 17:50
  • Asked here, thanks - https://stackoverflow.com/questions/65148708/testing-a-cloud-function-from-trigerring-event-option – Prany Dec 04 '20 at 18:17