python - 如何在 python 中向 Gmail-API 发送批量请求?

标签 python google-api gmail gmail-api google-api-python-client

我目前正在编写一个与 Gmail-API 配合使用的小型 Python 脚本。我正在尝试向 gmail 服务器发送批量请求。由于 gmail 用于发送批量请求的 native 方法在 2020 年 8 月被弃用,我必须自己构建一个。它必须采用“多部分/混合”的形式。

根据文档,它必须如下所示( https://developers.google.com/gmail/api/guides/batch ): Example batch request according to the gmail api documentation

我尝试使用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/

相关文章:

javascript - 使用 Gmail Apps 脚本以 HTML 和普通格式发送电子邮件

python - 有没有办法在继承过程中保留装饰器?

python - 从python的特定程序打开文件

android - 谷歌地图 API key 在侧面加载时适用于发布版本,在发布时不起作用

c# - 从 C# 应用程序发送邮件

c++ - 使用 Indy 组件,我得到 "connection closed gracefully"错误,但只在某些计算机上

python - 当我将组合框选择为特定值时,如何禁用文本ctrl?

python - 使用generate_blob_sas()时为blob生成的SAS URL不正确?

python - 如何解决 Google calendar API 中的 Http Error 403 "Insufficient Permission"?

javascript - Google+ 登录自定义按钮和通话