我已经实现了 python-social-auth我的 Django 项目中的 Google OAuth2 库,并且能够成功地让用户登录。该库存储在 Google 的 OAuth2 流程的响应中收到的 access_token。
我的问题是:google-api-python-client 的使用似乎依赖于创建和授权 credentials 对象,然后使用它来构建 API service,如下所示:
...
# send user to Google consent URL, get auth_code in response
credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())
from apiclient.discovery import build
service = build('gmail', 'v1', http=http_auth)
# use service for API calls...
由于我从 python-social-auth 提供的 access_token 开始,我该如何为 future 的 API 调用创建和授权 API 客户端服务?
编辑:澄清一下,上面的代码来自谷歌提供的示例。
请您参考如下方法:
鉴于您已经拥有 OAuth2 访问 token ,您可以使用 AccessTokenCredentials类(class)。
The oauth2client.client.AccessTokenCredentials class is used when you have already obtained an access token by some other means. You can create this object directly without using a Flow object.
例子:
import httplib2
from googleapiclient.discovery import build
from oauth2client.client import AccessTokenCredentials
credentials = AccessTokenCredentials(access_token, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('gmail', 'v1', http=http)
