[英]Why does the Gmail API returns 401 error?
我向 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}"
行中添加什么?
提前致謝!
如評論中所述,您在Authorization
header 中提供了credentials
實例:
"Authorization": f"Bearer {creds}"
您應該提供憑證的access_token
:
"Authorization": f"Bearer {creds.token}"
正如我的問題下面的評論中指出的那樣,我的錯誤是我確實提供了憑據的實例,而不是令牌本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.