谷歌存储Python API - 上传StringIO对象

4

我已经成功将文件上传到谷歌存储中,但我想跳过创建文件的步骤,直接使用StringIO并在谷歌存储中直接创建文件。

由于我对Python很陌生,所以我尝试使用上传已创建文件的标准方法:

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)

但是我遇到了错误: TypeError: 期望字符串或缓冲区 但是既然我已经给出了StringIO对象,我不知道为什么这不能工作?
3个回答

8
希望这仍然相关。但您可以尝试使用blob.upload_from_string方法。
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')

请注意,如果您想将文件保存为其他文件类型,则需要修改content_type参数。我以“text/csv”为例。默认值为“text/plain”。

虽然这个答案是正确的,但是一旦查看源代码,upload_from_string只是将字符串转换为ByteIO以便于upload_from_filename上传。 - MT-FreeHK

0

因为您正在上传文件名。但应该从文件对象上传。应该是:

blob.upload_from_file(buffer)

-1

我不确定您如何调用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))

好的,我尝试过了,但是当我尝试使用buffer(StringIO对象)而不是文件时,我得到了TypeError:期望字符串或缓冲区... - Tomislav Mikulin
你可以尝试使用 blob.upload_from_filename(filename='/local/path.txt') 吗? - patilnitin
1
是的,我做了类似的事情,但我想直接上传StringIO对象 - 而不是先创建一个文件,然后再上传它! - Tomislav Mikulin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接