【发布时间】:2021-08-12 17:04:09
【问题描述】:
我向 gmail 发送批处理请求后的响应与文档 (https://developers.google.com/gmail/api/guides/handle-errors#exponential-backoff) 中描述的相同:
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
我的请求代码是:
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
elif not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run.
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
gmailUrl = "https://gmail.googleapis.com/batch/gmail/v1"
request_header = {"Authorization": f"Bearer {creds}", "Host": "www.googleapis.com", "Content-Type": "multipart/mixed; boundary=boundary"}
body = []
for n in message_Ids:
boundary = "--boundary\n"
content_type = "Content-Type: application/http\n\n"
request = f'GET /gmail/v1/users/me/messages/{n}\n'
requestObj = boundary + content_type + request + "Accept: application/json; charset=UTF-8\n"
body.append(requestObj)
body.append("--boundary")
body = "\n".join(body)
response = req.post(url=gmailUrl, headers=request_header, data=body, auth=)
pprint(response)
pprint(response.text)
当我设法以某种方式从 gmail 服务器获得响应时,我想我的请求已被接受。 但我不明白为什么会收到 401 错误。 如果我将 GET 请求作为单个请求发送,我的应用程序可以正常工作。
我必须在"Autorization": f"Bearer {creds}" 行中输入什么内容?
提前致谢!
【问题讨论】:
-
不使用官方库有什么原因吗?能否提供
creds相关的代码? -
gmail 库中没有 get-method 的批处理请求。请参阅文档:developers.google.com/gmail/api/guides/batch
-
库中支持批量请求,ref。此外,在
"Autorization": f"Bearer {creds}",您应该提供访问令牌,而您将提供credentials 的实例。要提供访问令牌,请使用creds.token,因此请改用"Autorization": f"Bearer {creds.token}"。 -
谢谢!我不太了解您提供的链接中的文档。我自己设法构建了一个自定义批处理请求,但是您链接到的方法似乎非常简单。不幸的是,我不太了解文档。回调或请求 ID 是什么意思?这里的例子:googleapis.github.io/google-api-python-client/docs/batch.html 没有让我更进一步。
-
我设法让它工作了!但我似乎并没有真正理解这让我很困扰。
标签: python google-api gmail-api