当access_token无效时,Google Calendar API

时间:2015-01-24 01:09:23

标签: python google-calendar-api

我试图在某人的谷歌日历中获取特定日期范围的事件。我正在做以下事情:

    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。这个用例怎么会失败呢?在这里我有什么问题需要刷新令牌吗?

我在下面阅读了以下内容:

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

Google access token expiration time

1 个答案:

答案 0 :(得分:0)

尝试测试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