我必须多久登录一次 Gmail API?

How often do I have to login with Gmail API?

我有一个 python 脚本(并且有效),它运行一整天,使用 Gmail API 在我的电子邮件中搜索,就像这样

def login():
    SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
    store = file.Storage(os.path.join(script_path, 'token.json'))
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets(os.path.join(script_path, 'credentials.json'), SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('gmail', 'v1', credentials=creds)
    return service

def search(service):
    .
    .
    .
    return data

但是我不想调用 login() 超过我必须的次数,所以,我的问题是...

我需要多久 login() 更新 'service' 变量?

在 'token.json' 中有 2 个键:"token_expiry" 和 "expires_in"。我认为其中之一有答案,但我不确定,是每小时一次还是直到令牌到期?

"token_expiry": "2019-03-04T20:00:48Z",
"token_response": {
    "expires_in": 3600

下面来自 Google 的 url 有您需要的答案。基本上它会检查您是否有令牌以及它是否仍然有效。如果已经过期并且 access_token 有 refresh_token,那么它将刷新令牌,如果无效则它将请求一个新令牌。

https://developers.google.com/gmail/api/quickstart/python

"token_expiry": "2019-03-04T20:00:48Z",
"token_response": {
    "expires_in": 3600

代码 return 对您来说是一个访问令牌。访问令牌在一小时后过期 3600 Seconds = 60 Minutes 你应该只需要每 55 分钟刷新一次(有一种叫做时钟偏差的东西,这就是为什么我不说每 60 分钟)

您可以做的另一件事是,如果您遇到未经授权的错误,请保持 运行 正常运行您的代码,然后捕获该错误并 运行 您的登录名,然后重试。

您可能还需要考虑检查 python 客户端库,看看它是否可以处理刷新令牌,这将允许您的代码根据需要刷新访问权限,而您无需担心。