使用OAuth2.0导入Google联系人

8

有哪些使用Python和oauth2.0导入Google联系人的可能方法?

我们成功获取了凭据,应用程序请求访问联系人,但在获得凭据后,我找不到发现联系人API的方法。

因此,诸如以下内容的东西:

 from apiclient.discover import build
 import httplib2
 http = httplib2.Http()
 #Authorization
 service = build("contacts", "v3", http=http) 

出现了 UnknownApiNameOrVersion 异常。看起来联系人API不在支持的API列表中。

我正在寻找替代方法。

2个回答

21

Google Contacts API无法与google-api-python-client库一起使用,因为它是一个Google Data API,而google-api-python-client旨在与基于发现的API一起使用。

不必像@NikolayFominyh描述的那样费事,您可以在gdata-python-client中使用OAuth 2.0的本地支持。

要获取有效的令牌,请按照谷歌开发人员博客文章中的说明进行操作,以深入了解该过程。

首先,创建一个令牌对象:

import gdata.gauth

CLIENT_ID = 'bogus.id'  # Provided in the APIs console
CLIENT_SECRET = 'SeCr3Tv4lu3'  # Provided in the APIs console
SCOPE = 'https://www.google.com/m8/feeds'
USER_AGENT = 'dummy-sample'

auth_token = gdata.gauth.OAuth2Token(
    client_id=CLIENT_ID, client_secret=CLIENT_SECRET,
    scope=SCOPE, user_agent=USER_AGENT)

然后,使用此令牌授权您的应用程序:

APPLICATION_REDIRECT_URI = 'http://www.example.com/oauth2callback'
authorize_url = auth_token.generate_authorize_url(
    redirect_uri=APPLICATION_REDIRECT_URI)

生成此authorize_url后,您(或您应用的用户)需要访问并接受OAuth 2.0提示。如果在Web应用程序中,则可以简单地重定向,否则您需要在浏览器中访问链接。

授权后,将代码交换为令牌:

import atom.http_core

redirect_url = 'http://www.example.com/oauth2callback?code=SOME-RETURNED-VALUE'
url = atom.http_core.ParseUri(redirect_url)
auth_token.get_access_token(url.query)

如果您访问的是浏览器,您需要将重定向到的URL复制到变量redirect_url中。

如果您在Web应用程序中,您将能够指定处理程序以处理路径/oauth2callback(例如),并可以简单地检索查询参数code以交换代码获取令牌。例如,如果使用WebOb

redirect_url = atom.http_core.Uri.parse_uri(self.request.uri)

最后,用这个令牌授权您的客户端:

import gdata.contacts.service

client = gdata.contacts.service.ContactsService(source='appname')
auth_token.authorize(client)

更新(原始回答12个月后):

或者您可以像我在博客文章中所描述的那样使用google-api-python-client支持。


太好了!这正是我问这个问题时想要的答案! - Nikolay Fominyh
在我的重定向处理程序视图“oauth2callback”中,我无法访问在初始视图中创建的auth_token对象。你知道如何实现这个吗? - katericata

2

最终的解决方案相对容易。

步骤1 获取oauth2.0令牌。官方文档中有详细说明: http://code.google.com/p/google-api-python-client/wiki/OAuth2

步骤2 现在我们有了令牌,但是无法发现联系人API。 但是您可以在oauth2.0 playground中导入联系人。 https://code.google.com/oauthplayground/

您会发现,在步骤1中获得的凭据中有访问令牌。 要访问联系人API,您必须将以下参数添加到标头中:'Authorization':'OAuth %s' % access_token

步骤3 现在,您必须传递与oauth1.0令牌兼容的令牌给Google库。 可以通过以下代码完成:

from atom.http import ProxiedHttpClient #Google contacts use this client
class OAuth2Token(object):
    def __init__(self, access_token):
        self.access_token=access_token

    def perform_request(self, *args, **kwargs):
        url = 'http://www.google.com/m8/feeds/contacts/default/full'
        http = ProxiedHttpClient()
        return http.request(
            'GET',
            url,
            headers={
                'Authorization':'OAuth %s' % self.access_token
            }
        )
google = gdata.contacts.service.ContactsService(source='appname')
google.current_token = OAuth2Token(oauth2creds.access_token)
feed = google.GetContactsFeed()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接