我使用Oauth连接帐户,编写了一个小应用程序来清除Google搜索控制台(正式的Google网站管理员工具)中的错误。这在过去两周运行良好,但是,今天我注意到以下错误:
Traceback (most recent call last):
File "/home/graingerkid/search_console_auto/scripts/error_count.py", line 97, in <module>
get_error_stats()
File "/home/graingerkid/search_console_auto/scripts/error_count.py", line 19, in get_error_stats
access_token = get_refreshed_tokens(refresh_token)
File "/home/graingerkid/search_console_auto/scripts/refresh_token.py", line 25, in get_refreshed_tokens
access_token = keys['access_token']
KeyError: 'access_token'
在调查并尝试调试我的代码后,我意识到在使用access_token
请求时,我没有得到refresh_token
,这是输出:
{
"error" : "invalid_grant"
}
这是我写的用来抓住access_tokens
的函数(我已经更改了敏感信息):
#-*- coding:utf-8 -*-
import json
import httplib2
import urllib
import pprint
def get_refreshed_tokens(refresh_token):
GOOGLE_CLIENT_ID = '98997543650-f0tn93u86vmts4j2m987654359shue6gu9g.apps.googleusercontent.com'
GOOGLE_CLIENT_SECRET = 'TFGZVLVG7VtnnrbNDTYFNBRgbfdFuENkBY'
h = httplib2.Http(".cache")
url = 'https://accounts.google.com/o/oauth2/token'
body = {
'client_secret': GOOGLE_CLIENT_SECRET,
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': GOOGLE_CLIENT_ID
}
headers = {'Content-type': 'application/x-www-form-urlencoded', 'cache-control': 'no-cache'}
response, content = h.request(url, 'POST', headers=headers, body=urllib.urlencode(body))
print content
keys = json.loads(content)
try:
access_token = keys['access_token']
except Exception as e:
pass
access_token = None
return access_token
get_refreshed_tokens('1/lWS6Fu3Hz5dMBPk9huVu6mt5yrnj5hrunhMEf7vs_UdibrBactUREZofsF9C7PrpE-j')
在请求访问用户帐户时,我使用以下内容:
google = oauth.remote_app('google',
base_url='https://www.google.com/accounts/',
authorize_url='https://accounts.google.com/o/oauth2/auth',
request_token_url=None,
request_token_params={'scope': 'https://www.googleapis.com/auth/webmasters https://www.googleapis.com/auth/userinfo.email',
'response_type': 'code',
'access_type':'offline',
'approval_prompt':'force'},
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_method='POST',
access_token_params={'grant_type': 'authorization_code'},
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET)
请记住,这几周工作正常,我很难理解出了什么问题,搜索SO并没有得出答案。
任何人都可以帮忙吗?
(与我们相关的帐户是我的,我已检查过他们的访问权限,并且Google API控制台中的API访问权限仍然完整,没有任何变化。)