【问题标题】:How to authorize a Python Google API client service given an OAuth2 access_token?如何在给定 OAuth2 access_token 的情况下授权 Python Google API 客户端服务?
【发布时间】:2017-05-03 09:52:50
【问题描述】:

我已经在我的 Django 项目中为 Google OAuth2 实现了 python-social-auth 库,并且能够成功地使用它登录用户。该库存储在 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 开始,我如何创建和授权 API 客户端 service 以供将来的 API 调用?

编辑:澄清一下,上面的代码来自谷歌提供的示例。

【问题讨论】:

    标签: python google-oauth google-api-python-client python-social-auth oauth2client


    【解决方案1】:

    鉴于您已经拥有 OAuth2 访问令牌,您可以使用 AccessTokenCredentials 类。

    oauth2client.client.AccessTokenCredentials 类在您已经通过其他方式获得访问令牌时使用。您可以直接创建此对象,而无需使用 Flow 对象。

    例子:

    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)
    

    【讨论】:

    【解决方案2】:

    您可以查看 Google Guide API 提供的示例,例如:通过 gmail 应用程序发送电子邮件,https://developers.google.com/gmail/api/guides/sending

    【讨论】:

    • 不幸的是,所有这些代码(我找到的)都假定您拥有service: Authorized Gmail API service instance - 我还没有弄清楚如何在给定access_token的情况下授权service
    【解决方案3】:

    如果你有一个已经刷新的未过期的最新访问令牌,那么你可以得到service变量为:

    from googleapiclient.discovery import build
    from google.oauth2.credentials import Credentials
    
    
    creds = Credentials("<ACCESS_TOKEN>")
    service = build('gmail', 'v1', credentials=creds)
    
    # Call the Gmail API
    
    

    【讨论】:

      猜你喜欢
      • 2013-08-21
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 2013-01-22
      • 2017-02-22
      • 1970-01-01
      • 2020-09-23
      • 2017-09-07
      相关资源
      最近更新 更多