我正在使用谷歌提供的 Python API。我想要做的只是确保访问 token 不会过期。我将 refresh_token 存储在凭据文件中。我只是不确定如何在调用 API 之前“检查” token 是否仍然有效,以及是否需要刷新 token 并将其重新存储在凭据文件中。
我做了一个测试,即使我从凭证文件中删除访问 token ,它也会使用刷新 token 将它们重写到其中。我希望这也适用于过期的访问 token 。
谢谢
storage = Storage('cred_storage.txt')
credentials = storage.get()
if not credentials:
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
storage.put(credentials)
http = httplib2.Http()
http = credentials.authorize(http)
print http
service = build('admin', 'reports_v1', http=http)
print service
data_query = service.customerUsageReports().get(**{'date':'2015-01-07'})
feed = data_query.execute()
print feed
最佳答案
只需检查过期访问 token 的大小写并像这样刷新过期的访问 token :
if credentials.access_token_expired:
credentials.refresh(httplib2.Http())
提示:在开发这个时,您可以通过编辑凭证文本文件中的访问 token 到期日期并强制它早于一个小时来进行测试
此外,在您检查 if not credentials:
的代码行中,您可以更好地处理这种情况:
if credentials is None or credentials.invalid:
关于python - 如何刷新存储的 Google oAuth 凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29154374/