2017-12-27 164 views
0

我成功地将文件上传到谷歌存储,但我想跳过创建一个文件,并使用StringIO而不是直接在谷歌存储上创建文件。谷歌存储python API - 上传一个StringIO对象

由于我是新来的蟒蛇,我只是想用我用于上传所创建的文件的标准方法:

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) 

但我得到的错误:

类型错误:预期字符串或缓冲区

但是因为我给了它的StringIO对象,我不知道为什么这不起作用?

回答

0

我不确定你怎么调用cloud_upload函数,但你可以简单地使用upload_from_filename函数来满足你的需要。

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)) 
+0

好,我试过了,但我得到类型错误:预期的字符串或缓冲区...当我尝试使用缓冲区(StringIO对象),而不是一个文件... –

+0

你可以尝试用'blob.upload_from_filename (filename ='/ local/path.txt')'? – patilnitin

+0

是的,我做了这样的事情,但我想直接上传StringIO对象 - 不先创建文件,然后上传它! –