Using Google API Refresh Token in Python

耗尽温柔 提交于 2019-12-11 06:10:49

问题


I made a personal use app that just queries my gmail for a certain type of email. The app is successfully running on a pi night and day making requests to the Gmail service every thirty seconds.

However every week or so I get this error:

messages = gmail.users().messages().list(userId='me').execute() # 
q='is:unread'
File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- 
packages\oauth2client\_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- 
packages\googleapiclient\http.py", line 839, in execute
method=str(self.method), body=self.body, headers=self.headers)
File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- 
packages\googleapiclient\http.py", line 166, in _retry_request
resp, content = http.request(uri, method, *args, **kwargs)
File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- 
packages\oauth2client\transport.py", line 186, in new_request
credentials._refresh(orig_request_method)
File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- 
packages\oauth2client\client.py", line 761, in _refresh
self._do_refresh_request(http)
File "C:\Users\rexma\Anaconda3\envs\stan_env\lib\site- 
packages\oauth2client\client.py", line 819, in _do_refresh_request
raise HttpAccessTokenRefreshError(error_msg, status=resp.status)
oauth2client.client.HttpAccessTokenRefreshError: invalid_grant: Token has 
been expired or revoked.

Which forces me to go back in, delete my old credentials and rerun the authorization. I've tried to do the other fixes online like setting

flow.authorization_url(access_type = 'offline', approval_prompt='force')

But the 'OAuth2WebServerFlow' object has no attribute 'authorization_url'.

Here is my full authorization code:

def authenticate(CLIENT_SECRET_FILE, APPLICATION_NAME, SCOPE, credential_name):
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, credential_name)

store = Storage(credential_path)
credentials = store.get()

if not credentials or credentials.invalid:
    flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPE)
    flow.user_agent = APPLICATION_NAME
    # flow.authorization_url(access_type='offline', approval_prompt='force')
    credentials = run_flow(flow, store)

return credentials

I'm definitely still a scrub with OAuth2, even having read this. I just want to know how I can have my app use the refresh token in the json credentials to keep running without expiring.

Any help is much appreciated.

来源:https://stackoverflow.com/questions/49709197/using-google-api-refresh-token-in-python

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