【问题标题】:google storage python API - uploading an StringIO object谷歌存储 python API - 上传 StringIO 对象
【发布时间】:2017-12-27 13:31:48
【问题描述】:

我成功将文件上传到谷歌存储,但我想跳过创建文件并改用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 对象,我不知道为什么这不起作用?

【问题讨论】:

    标签: python google-cloud-platform stringio


    【解决方案1】:

    希望这仍然是相关的。但是你可以尝试使用 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 上传。
    【解决方案2】:

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

    blob.upload_from_file(buffer)
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 好吧,我试过了,但我得到 TypeError: expected string or buffer...当我尝试使用缓冲区(StringIO 对象)而不是文件时...
      • 你可以试试blob.upload_from_filename(filename='/local/path.txt') 吗?
      • 是的,我做了类似的事情,但我想直接上传 StringIO 对象 - 无需先创建文件然后上传!
      猜你喜欢
      • 1970-01-01
      • 2020-07-04
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多