访问令牌无效时的Google日历API

2024-05-23 18:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在谷歌日历上获取特定日期范围内的事件。我正在做以下工作:

    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(),我得到以下错误:

^{pr2}$

当我使用断点时,它从不在if语句中说access_token_expired。这怎么可能总是让用例失败呢?我在刷新代币的时候有什么地方做错了吗?在

关于这一点,我读了以下内容:

http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-4.2.2

Google access token expiration time


Tags: tokenjsonhttpexecuteifaccessservicedt
1条回答
网友
1楼 · 发布于 2024-05-23 18:11:41

尝试测试credentials.invalid

我有一个小程序,我用它来确保存储的凭证对于gmail单元测试来说总是新鲜的。它可能/可能不适合你的情况。

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

相关问题 更多 >