我正在使用requests
Google Drive API“分段”上传。
该email.mime
解决方案不适用于 Google 的 API,因此我深入研究了requests
源代码以了解它是如何实现multipart/form-data
主体的。
requests
使用urllib3.filepost.encode_multipart_formdata()
帮助器,它可以被包装以提供multipart/related
:
from urllib3.filepost import encode_multipart_formdata, choose_boundary
def encode_multipart_related(fields, boundary=None):
if boundary is None:
boundary = choose_boundary()
body, _ = encode_multipart_formdata(fields, boundary)
content_type = str('multipart/related; boundary=%s' % boundary)
return body, content_type
现在我们可以encode_multipart_related()
用来创建一个(body, content_type)
符合 Google 要求的元组:
import json
from urllib3.fields import RequestField
def encode_media_related(metadata, media, media_content_type):
rf1 = RequestField(
name='placeholder',
data=json.dumps(metadata),
headers={'Content-Type': 'application/json; charset=UTF-8'},
)
rf2 = RequestField(
name='placeholder2',
data=media,
headers={'Content-Type': media_content_type},
)
return encode_multipart_related([rf1, rf2])
这是一个完整的示例,它使用我们encode_media_related()
的库将 hello world 文件上传到 Google Drive google_auth
。
from google.oauth2 import service_account
import google.auth.transport.requests
credentials = service_account.Credentials.from_service_account_file(
PATH_TO_SERVICE_FILE,
scopes=['https://www.googleapis.com/auth/drive.file'],
)
session = google.auth.transport.requests.AuthorizedSession(credentials)
metadata = {
'mimeType': 'application/vnd.google-apps.document',
'name': 'Test Upload',
}
body, content_type = encode_media_related(
metadata,
'<html><body><p>Hello World!</body></html>',
'text/html; charset=UTF-8',
)
resp = session.post(
'https://www.googleapis.com/upload/drive/v3/files',
data=body,
params={'uploadType': 'multipart'},
headers={'Content-Type': content_type},
)
print 'Uploaded to file with id: %s' % resp.json()['id']