Reputation: 5936
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?
Upvotes: 4
Views: 3183
Reputation: 183
Cause you are uploading from filename. But should upload from file object rather. Should be:
blob.upload_from_file(buffer)
Upvotes: 0
Reputation: 367
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'.
Upvotes: 8
Reputation: 1171
I am not sure how are you invoking the cloud_upload
function but you can simply use the upload_from_filename
function to satisfy your need.
def upload_blob(self, bucket_name, source_file_name, 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_filename(source_file_name)
print('File {} uploaded to {}.'.format(
source_file_name,
destination_blob_name))
Upvotes: -1