【问题标题】:Google Drive API - Uploading from MediaFileUpload using blobGoogle Drive API - 使用 blob 从 MediaFileUpload 上传
【发布时间】:2018-02-16 16:38:12
【问题描述】:

我正在尝试通过 v3 API 将文件 (pdf) 上传到 Google Drive,我想从电子邮件的附件中创建文件。我发现的所有文档似乎都依赖于我想上传 Blob 的本地文件。

到目前为止,这是我的代码的精髓:

class MailHandler(InboundMailHandler):
  def receive(self, mail_message):
    logging.info("Received a message from: " + mail_message.sender)
    if hasattr(mail_message, 'attachments'):
      logging.info("Has attachments")
      for filename, filecontents in mail_message.attachments:
        file_blob = filecontents.payload.decode(filecontents.encoding)
        credentials = UserModel.query().get()
        media = MediaFileUpload(filename, mimetype = 'image/jpg')
        file = drive.files().create( body = {'name': 'testupload.jpg'}, media_body = media)
        file.execute(c.credentials.authorize(http))

这会引发错误,因为文件不存在,而不是因为它是 blob。

有人可以帮帮我吗?

【问题讨论】:

    标签: python google-drive-api


    【解决方案1】:

    最后,关键是使用apiclient.http模块中的MediaInMemoryUpload,我通过检查http找到了。

    以下是如何使用它的粗略概述:

    from apiclient.http import MediaInMemoryUpload
    media = MediaInMemoryUpload(file_blob, mime_type, resumable=True)
    file = drive.files().create(body={'name': filename},media_body=media)
    file.execute()
    

    【讨论】:

    • "已弃用:将 MediaIoBaseUpload 与 io.TextIOBase 或 StringIO 一起用于流。"
    【解决方案2】:

    试试这个UploaderForGoogleDrive 示例,了解 DrPaulBrewer 如何将 blob 文件上传到 Drive API:

    sn-p:

    **
         * Helper class for resumable uploads using XHR/CORS. Can upload any Blob-like item, whether
         * files or in-memory constructs.
         *
         * @example
         * var content = new Blob(["Hello world"], {"type": "text/plain"});
         * var uploader = new MediaUploader({
         *   file: content,
         *   token: accessToken,
         *   onComplete: function(data) { ... }
         *   onError: function(data) { ... }
         * });
         * uploader.upload();
    

    查看整个代码实现的链接。

    【讨论】:

    • 除非我遗漏了一些东西,否则这是一个客户端 javascript 函数,我问的是服务器端 python 问题?
    猜你喜欢
    • 2016-02-12
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多