2014-01-29 61 views
0

我是新来的Python和新API的工作,所以这可能是基本的......我可以让我的初始请求,导致浏览器窗口打开。此时,用户必须在Google同意页面上进行选择。之后,授权码被返回......我明白了。我的问题是,如何暂停运行Python代码,以便我可以等待用户权限并存储下一步所需的代码?我只是用它们的库在Python 2.7中测试它,但我坚持这一点。我可以在箭头上放什么?感谢任何帮助。谷歌联系人API:存储授权码并交换令牌

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) 

回答

0

下面是一些示例代码,用于处理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

+0

它实际上是基于网络的服务器,但我是测试没有建立一个网络服务器,所以我真的没有办法存储附加到我的重定向的代码。我正在使用已安装的应用程序重定向作为最后的努力,我认为无论如何都没有意义。是否有一个Web应用程序的等效库? – RAW

+0

太好了,谢谢你指出我正确的方向。 – RAW