python - 用于在没有 Google Driver UI 的情况下将大文件上传到 Google Drive 的 POST 消息

标签 python google-app-engine google-drive-api

我的理解是,要使用 API 版本 2 从我自己的应用程序将大文件上传到 Google 云端硬盘,我应该发送如下消息。不幸的是,我不知道如何使用 Python 为多部分消息实现这种格式。有没有人有示例 Python 代码可以让我朝着正确的方向前进?

谢谢, 克里斯


POST /upload/drive/v2/files?uploadType=multipart

Authorization: Bearer <Access token>
Content-Length: <length>
Content-Type: multipart/related; boundary="<a base64 encoded guid>"

--<a base64 encoded guid>
Content-Type: application/json

{"title": "test.jpg", "mimeType":"image/jpeg", "parents":[]}
--<a base64 encoded guid>
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<base64 encoded binary data>
--<a base64 encoded guid>--

最佳答案

Google Drive API 的引用指南包含多种语言的代码片段,包括适用于所有 API 端点的 Python。

对于您的用例,drive.files.insert端点有答案:

from apiclient import errors
from apiclient.http import MediaFileUpload
# ...

def insert_file(service, title, description, parent_id, mime_type, filename):
  """Insert new file.

  Args:
    service: Drive API service instance.
    title: Title of the file to insert, including the extension.
    description: Description of the file to insert.
    parent_id: Parent folder's ID.
    mime_type: MIME type of the file to insert.
    filename: Filename of the file to insert.
  Returns:
    Inserted file metadata if successful, None otherwise.
  """
  media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
  body = {
    'title': title,
    'description': description,
    'mimeType': mime_type
  }
  # Set the parent folder.
  if parent_id:
    body['parents'] = [{'id': parent_id}]

  try:
    file = service.files().insert(
        body=body,
        media_body=media_body).execute()

    return file
  except errors.HttpError, error:
    print 'An error occured: %s' % error
    return None

关于python - 用于在没有 Google Driver UI 的情况下将大文件上传到 Google Drive 的 POST 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11441100/

相关文章:

python - 如何使用 pyaudio 播放立体声 aiff 文件?

python - unicode Python 字符串中的字节数

python - 如何在不使用 for 循环或 try 语句的情况下有效地将货币符号和数字拆分为一个字符串

node.js - Google App Engine 上的 Sails.js 套接字问题

python - 使用诱变剂从Google驱动器加载音频文件的元数据

python - 使用 print (", ".join(my_array)) 提取单个字符串并将其添加到 Streamlit Markdown 中。我没有得到字符串,而是没有得到任何东西

php - 尝试使用 Google SQL Cloud 在 Google App Engine 上运行 Wordpress

python - GoogleAppEngineLauncher 在哪里保存本地日志文件?

android - 从 Android 使用 Google Drive SDK

java - 代理背后的 Google Drive API Java 客户端