1

我制作了一个个人使用的应用程序,它只在我的 gmail 中查询某种类型的电子邮件。该应用程序在 pi 日夜成功运行,每 30 秒向 Gmail 服务发出请求。

但是每周左右我都会收到此错误:

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.

这迫使我回去,删除我的旧凭据并重新运行授权。我已经尝试在线进行其他修复,例如设置

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

但是“OAuth2WebServerFlow”对象没有“authorization_url”属性。

这是我的完整授权码:

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

即使读过这篇文章,我仍然对 OAuth2 很感兴趣。我只想知道如何让我的应用程序使用 json 凭据中的刷新令牌来保持运行而不会过期。

任何帮助深表感谢。

4

0 回答 0