0

有没有办法将刷新令牌与 Google 目录服务 API 一起使用?我找不到任何示例(我正在使用 Python)。我正在寻找类似于以下代码的内容(这适用于 Google Adwords API),并具有预先设置的凭据:

oauth2_client = oauth2.GoogleRefreshTokenClient(
    CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN)

adwords_client = adwords.AdWordsClient(
    DEVELOPER_TOKEN, oauth2_client, USER_AGENT, CLIENT_CUSTOMER_ID)

self.managed_customer_service = adwords_client.GetService(
    'ManagedCustomerService', version='v201402')

对于 Directory API,我只找到了以下代码片段,但我不知道如何使用刷新令牌:

flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)

# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)

self.directory_service = build('admin', 'directory_v1', http=http)

我的最终目标是仅使用刷新令牌授权我的应用程序,而无需每次打开浏览器、登录并获取新令牌。

4

1 回答 1

0

如果您使用 Storage 对象,Python 客户端库可以自动存储、加载和刷新凭据。Gmail API Python 快速入门示例展示了如何使用文件存储,它将凭据保存到磁盘。以下是相关的代码行:

from oauth2client.file import Storage
from oauth2client.tools import run

...

# Location of the credentials storage file
STORAGE = Storage('gmail.storage')

...

# Try to retrieve credentials from storage or run the flow to generate them
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
  credentials = run(flow, STORAGE, http=http)

客户端库中内置了其他存储类,或者您可以扩展Storage基类以实现您自己的。

于 2014-11-07T18:58:43.340 回答