![](/img/trans.png)
[英]Google Calendar API: Error code 403: The request is missing a valid API key
[英]Why does Gmail API fail with a 403 error, using code that works properly for Google Calendar API?
我正在關注這些指南: https : //developers.google.com/google-apps/calendar/quickstart/python,https : //developers.google.com/gmail/api/quickstart/python 。
我已完成兩者的所有設置步驟,日歷API代碼工作正常,而Gmail API代碼失敗,出現403錯誤。 是什么導致了這個? 這兩個API之間有什么不同?
我結合了這兩個不同示例中的代碼,因此他們盡可能多地共享API設置代碼,以排除那里的錯誤。
我已在Google開發者控制台中停用並重新啟用了Gmail API。
如前所述在這里 ,我已經啟用聯系人和Google+的API。
正如這里提到的,我已經嘗試了Gmail范圍的所有三種組合 - 只是示例中的范圍,只是' https://mail.google.com/ ',或兩者兼而有之。
這個答案,以及其他幾個來源,建議'將“Referers”設置為“允許任何引用”,但是我可以找到包含此選項的Dev Console中沒有頁面。 我可以通過“域驗證”標簽添加域名,但這似乎不會影響任何內容。
碼:
import httplib2
import os
from pprint import pprint
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
import datetime
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
class GoogleApi(object):
client_secret_file = 'client_secret.json'
application_name = 'test_app'
def __init__(self):
self.credentials = self.get_credentials()
self.http = self.credentials.authorize(httplib2.Http())
self.service = discovery.build(self.api_name, self.api_version, http=self.http)
def get_credentials(self):
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'test-app.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(self.client_secret_file, self.scopes)
flow.user_agent = self.application_name
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatability with Python 2.6
credentials = tools.run(flow, store)
print 'Storing credentials to ' + credential_path
return credentials
class CalendarApi(GoogleApi):
scopes = 'https://www.googleapis.com/auth/calendar.readonly'
api_name = 'calendar'
api_version = 'v3'
def get_calendar_ids(self):
cl = self.service.calendarList().list().execute()
ids = [x['id'] for x in cl['items']]
return ids
class GmailApi(GoogleApi):
scopes = 'https://mail.google.com/'
#scopes = 'https://www.googleapis.com/auth/gmail.readonly'
api_name = 'gmail'
api_version = 'v1'
def get_labels(self):
ml = self.service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
return labels
def main():
cc = CalendarApi()
ids = cc.get_calendar_ids()
print(ids)
m = GmailApi()
labels = m.get_labels()
print(labels)
if __name__ == '__main__':
main()
當前錯誤(“權限不足”):
Traceback (most recent call last):
File "gmail_api_test.py", line 92, in <module>
main()
File "gmail_api_test.py", line 87, in main
labels = m.get_labels()
File "gmail_api_test.py", line 76, in get_labels
ml = self.service.users().labels().list(userId='me').execute()
File "/usr/local/lib/python2.7/site-packages/oauth2client/util.py", line 140, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/googleapiclient/http.py", line 729, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Insufficient Permission">
先前版本的代碼出錯(“未配置訪問權限。您的項目未啟用API(Gmail API)。請使用Google Developers Console更新您的配置。”):
Traceback (most recent call last):
File "gmail_demo.py", line 71, in <module>
main()
File "gmail_demo.py", line 59, in main
results = service.users().labels().list(userId='me').execute()
File "/usr/local/lib/python2.7/site-packages/oauth2client/util.py", line 142, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/googleapiclient/http.py", line 729, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Access Not Configured. The API (Gmail API) is not enabled for your project. Please use the Google Developers Console to update your configuration.">
權限仍然不足的原因是因為文件中的refresh_token
仍然有效。 在驗證用戶身份時獲得的access_token
和refresh_token
僅具有您當時指定的范圍。
試想一下,如果不是這樣的話。 然后,您可以要求用戶為readonly
,並在以后添加包羅萬象https://mail.google.com/
-scope,做了很多額外的東西,而用戶的同意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.