Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to Google Cloud Storage from Cloud Function (python)

Tags:

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) 
like image 445
David Ferris Avatar asked Sep 10 '18 01:09

David Ferris


People also ask

How do I call a Google Cloud function from Python?

Go to the Google Cloud Console and the Cloud Functions dashboard. Select Create Function. Fill out the name of the function to use in the URL for the HTTP Trigger. Also choose the Trigger to use.

How do I import a CSV file into Google Cloud Storage?

Select All Settings > Raw Data Export > CSV Upload. Select Google Cloud Storage from the dropdown menu. Upload your Service Account Key credential file. This is the JSON file created in the Google Cloud Console. Enter your Google Cloud Storage bucket name.


1 Answers

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

like image 95
Dustin Ingram Avatar answered Oct 08 '22 09:10

Dustin Ingram