Google 日历 API 当 access_token 无效时

Google Calendar API when access_token is invalid

我正在尝试获取某人 google 日历中特定日期范围内的事件。我正在执行以下操作:

    credentials = AccessTokenCredentials.from_json(token_json)
    http = httplib2.Http()
    if credentials.access_token_expired:
        credentials.refresh(http)
    else:
        http = credentials.authorize(http)

    service = build(serviceName='calendar', version='v3', http=http)
    events = service.events().list(calendarId='primary', pageToken=None,
                                   timeMin=rfc3339(start_dt),
                                   timeMax=rfc3339(end_dt))
    events = events.execute()

出于某种原因,当我到达最后一行 events = events.execute() 时,出现以下错误:

AccessTokenCredentialsError: The access_token is expired or invalid and can't be refreshed.

当我使用断点时,它从不在我的 if 语句中显示 access_token_expired。这怎么能总是让那个用例失败呢?我在刷新令牌方面做错了什么吗?

我阅读了以下内容:

https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-22#section-4.2.2

Google access token expiration time

尝试测试 credentials.invalid?

我有一个小程序,用于确保存储的凭据对于 gmail 单元测试始终是最新的。它may/may不适合你的情况。

from oauth2client.client import OAuth2WebServerFlow
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools

# the stored credentials file to use for these tests
TEST_CREDENTIALS_FILE = 'testjoe.storage'


def get_credentials():
    """Utility routine to returns credentials for testing use"""

    # Location of the credentials storage file
    storage = Storage(TEST_CREDENTIALS_FILE)

    # Start the OAuth flow to retrieve credentials
    flow = flow_from_clientsecrets('client_secret_native.json', scope='https://www.googleapis.com/auth/gmail.modify')

    # Try to retrieve credentials from storage or run the flow to generate them
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        flags = tools.argparser.parse_args(args=[])
        credentials = tools.run_flow(flow, storage, flags)
    return credentials