google 存储 python API - 上传一个 StringIO 对象
google storage python API - uploading an StringIO object
我成功将文件上传到 google 存储,但我想跳过文件的创建并使用 StringIO 来创建文件google直接存储。
由于我是 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)
但我收到错误消息:
类型错误:预期的字符串或缓冲区
但是因为我给了它 StringIO 对象,我不知道为什么这不起作用?
我不确定你是如何调用 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))
希望这仍然有意义。但是你可以尝试使用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'.
因为您正在从 文件名 上传。但应该从文件对象上传。应该是:
blob.upload_from_file(buffer)
我成功将文件上传到 google 存储,但我想跳过文件的创建并使用 StringIO 来创建文件google直接存储。
由于我是 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)
但我收到错误消息:
类型错误:预期的字符串或缓冲区
但是因为我给了它 StringIO 对象,我不知道为什么这不起作用?
我不确定你是如何调用 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))
希望这仍然有意义。但是你可以尝试使用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'.
因为您正在从 文件名 上传。但应该从文件对象上传。应该是:
blob.upload_from_file(buffer)