Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a new file to a Google Cloud Storage bucket from a Google Cloud Function (Python)

I am trying to write a new file (not upload an existing file) to a Google Cloud Storage bucket from inside a Python Google Cloud Function.

  • I tried using google-cloud-storage but it does not have the "open" attribute for the bucket.

  • I tried to use the App Engine library GoogleAppEngineCloudStorageClient but the function cannot deploy with this dependencies.

  • I tried to use gcs-client but I cannot pass the credentials inside the function as it requires a JSON file.

Any ideas would be much appreciated.

Thanks.

like image 653
atron12 Avatar asked Nov 02 '25 21:11

atron12


2 Answers

You can now write files directly to Google Cloud Storage. It is no longer necessary to create a file locally and then upload it.

You can use the blob.open() as follows:

from google.cloud import storage

def write_file():
    client = storage.Client()
    bucket = client.get_bucket('bucket-name')
    blob = bucket.blob('path/to/new-blob.txt')
    with blob.open(mode='w') as f:
        for line in object: 
            f.write(line)

You can find more examples and snippets here: https://github.com/googleapis/python-storage/tree/main/samples/snippets

like image 168
moojen Avatar answered Nov 04 '25 11:11

moojen


 from google.cloud import storage
 import io

 # bucket name
 bucket = "my_bucket_name"

 # Get the bucket that the file will be uploaded to.
 storage_client = storage.Client()
 bucket = storage_client.get_bucket(bucket)

 # Create a new blob and upload the file's content.
 my_file = bucket.blob('media/teste_file01.txt')

 # create in memory file
 output = io.StringIO("This is a test \n")

 # upload from string
 my_file.upload_from_string(output.read(), content_type="text/plain")

 output.close()

 # list created files
 blobs = storage_client.list_blobs(bucket)
 for blob in blobs:
     print(blob.name)

# Make the blob publicly viewable.
my_file.make_public()
like image 37
André Duarte Avatar answered Nov 04 '25 12:11

André Duarte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!