Google API Python Client - AccessTokenRefreshError

三世轮回 提交于 2020-01-12 10:11:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!