Search code examples
pythongoogle-cloud-platformstringio

google storage python API - uploading an StringIO object


I succeeded in uplaoding a file to the google storage, but I would like to skip the creation of a file and use StringIO instead and create the file on the google storage directly.

Since I'm new to python, I just tried to use the standard method that I used for uploading the created file:

def cloud_upload(self, buffer, bucket, filename):
    buffer.seek(0)
    client = storage.Client()
    bucket = client.get_bucket(bucket)
    blob = bucket.blob(filename)
    blob.upload_from_filename(buffer)

But I get the error:

TypeError: expected string or buffer

But since I gave it the StringIO object, I don't know why this isn't working?


Solution

  • Hope this is still relevant. But you can try using blob.upload_from_string method

    def cloud_upload(self, buffer, bucket, filename):
        client = storage.Client()
        bucket = client.get_bucket(bucket)
        blob = bucket.blob(filename)
        blob.upload_from_string(buffer.getvalue(),content_type='text/csv')
    

    Do take note to modify the content_type parameter if you want to save the file as other file types. I placed 'text/csv' as an example. The default value is 'text/plain'.