【问题标题】:Google Contacts API: Storing the auth code and exchanging for tokenGoogle Contacts API:存储身份验证代码并交换令牌
【发布时间】:2014-01-30 07:12:46
【问题描述】:

我是 Python 新手,也是使用 API 的新手,所以这可能是基本的……我可以提出我的初始请求,这会导致浏览器窗口打开。此时,用户必须在 Google 同意页面上进行选择。之后返回授权码......我明白了。我的问题是,如何暂停我的 python 代码运行,以便等待用户许可并存储下一步所需的代码?我只是使用他们的库在 Python 2.7 中对其进行测试,但我坚持这一点。我可以在箭头上放什么?感谢任何帮助。

    from oauth2client.client import OAuth2WebServerFlow
    import webbrowser

    flow = OAuth2WebServerFlow(client_id=[id],
                       client_secret=[secret],
                       scope='https://www.google.com/m8/feeds',
                       redirect_uri='urn:ietf:wg:oauth:2.0:oob')

    auth_uri = flow.step1_get_authorize_url()
    webbrowser.open(auth_uri)

--->

    code=''
    credentials = flow.step2_exchange(code)

【问题讨论】:

    标签: api python-2.7 google-oauth google-contacts-api


    【解决方案1】:

    以下是一些针对 Web 服务器案例处理此问题的示例代码。 send_redirect 不是真正的方法,您首先需要将用户重定向到 Google,然后在您的回调中将授权代码交换为一组凭据。

    我还提供了一种使用 gdata 库返回的 OAuth2 凭据的方法,因为看起来您正在访问联系人 API:

    from oauth2client.client import flow_from_clientsecrets
    
    flow = flow_from_clientsecrets(
      "/path/to/client_secrets.json",
      scope=["https://www.google.com/m8/feeds"],
      redirect_url="http://example.com/auth_return"
    )
    
    # 1. To have user authorize, redirect them:
    send_redirect(flow.step1_get_authorize_url())
    
    # 2. In handler for "/auth_return":
    credentials = flow.step2_exchange(request.get("code"))
    
    # 3. Use them:
    
    import gdata.contacts.client
    import httplib2
    
    # Helper class to add headers to gdata
    class TokenFromOAuth2Creds:
      def __init__(self, creds):
        self.creds = creds
      def modify_request(self, req):
        if self.creds.access_token_expired or not self.creds.access_token:
          self.creds.refresh(httplib2.Http())
        self.creds.apply(req.headers)
    
    # Create a gdata client
    gd_client = gdata.contacts.client.ContactsClient(source='<var>YOUR_APPLICATION_NAME</var>')
    
    # And tell it to use the same credentials
    gd_client.auth_token = TokenFromOAuth2Creds(credentials)
    

    另见Unifying OAuth handling between gdata and newer Google APIs

    也就是说,您的问题中似乎已经包含大部分代码。希望这为您提供了一个更完整的示例来启动和运行。

    对于测试 - 如果您只是想在等待剪切和粘贴代码时暂停 Python 解释器,我会选择 code = raw_input('Code:') (http://docs.python.org/2/library/functions.html#raw_input)

    【讨论】:

    • 它实际上是基于网络服务器的,但是我在没有设置网络服务器的情况下进行了测试,所以我真的没有办法存储附加到我的重定向的代码。我使用已安装的应用程序重定向作为最后的努力,我想这无论如何都没有意义。是否有适用于网络应用的等效库?
    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2011-10-03
    • 2013-10-12
    相关资源
    最近更新 更多