我目前正在编写一个与 Gmail-API 配合使用的小型 Python 脚本。我正在尝试向 gmail 服务器发送批量请求。由于 gmail 用于发送批量请求的 native 方法在 2020 年 8 月被弃用,我必须自己构建一个。它必须采用“多部分/混合”的形式。
根据文档,它必须如下所示( https://developers.google.com/gmail/api/guides/batch ):
我尝试使用python请求库,但它似乎只支持“multipart/form”形式的请求。但我不确定。
# A list with all the message-id's.
messages = tqdm(gmail.list_messages('me'))
gmailUrl = "https://gmail.googleapis.com/batch/gmail/v1"
request_header = {"Host": "www.googleapis.com", "Content-Type": "multipart/mixed", "boundary"="bound"}
request_body = ""
# I want to bundle 80 GET requests in one batch.
# I don't know how to proceed from here.
for n in range(0,80):
response = req.post(url=gmailUrl, auth=creds, headers=request_header, files=request_body)
print(response)
所以我的问题非常简单:
如何使用 python 以“multipart/mixed”形式向 Gmail-API 发送 http 请求。
提前致谢!
最佳答案
您可以将每个请求添加到批处理中,然后执行该批处理。例如:
list_response = service.users().threads().list(userId='me').execute()
threads = list_response['threads']
bt = service.new_batch_http_request()
for thread in threads:
bt.add(service.users().threads().get(userId='me', id=thread['id']))
bt.execute()
bt 对象现在将具有字段 _requests 和 _responses,您现在可以访问它们 - 这将需要一些字符串解析(我使用 ast)。
关于python - 如何在 python 中向 Gmail-API 发送批量请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67658283/