问题
def get_code(request):
try:
user_info_service = get_service(request.user, 'oauth2', 'v2')
user_info = user_info_service.userinfo().get().execute()
if user_info and user_info.get('id'):
request.session['cur_user'] = user_info
return redirect('/me')
else:
raise NoUserIdException()
except AccessTokenRefreshError as atrfsh:
print atrfsh
print traceback.print_tb(sys.exc_info()[2])
except:
print "This was the exception..."
print sys.exc_info()
auth_uri = FLOW.step1_get_authorize_url()
print auth_uri
return redirect(auth_uri)
def get_service(user, name, version):
storage = Storage(CredentialsModel, 'id', user, 'credential')
credential = storage.get()
http = httplib2.Http()
http = credential.authorize(http)
service = build(name, version, http=http)
return service
I keep getting an AccessTokenRefreshError
on the user_info = user_info_service.userinfo()
.. line.
In the except block for AccessTokenRefreshError, it's printing 'invalid_grant'.
Upon reading the documentation for OAuth2Credentials
object: http://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.client.OAuth2Credentials-class.html#authorize, I found that the credential.authorize method in get_service
apparently should automatically perform a refresh of the access token.
What am I doing wrong that it's not able to refresh the access token?
回答1:
This is a workaround!
I have also been getting the same error approximately once every 10 calls to tasklists.list()
, so the problem is not unique to userinfo
.
The only solution that I've found is to put the API call in a retry loop. Doing an immediate retry fails, so I include a sleep before retrying. With a 45 second sleep, it works approximately 99.5% of the time.
I hope that someone can post a better solution.
来源:https://stackoverflow.com/questions/13982533/google-api-python-client-accesstokenrefresherror