Google联系人使用oauth2.0进行导入

Nik*_*nyh 8 python google-api contacts oauth-2.0 google-api-python-client

有哪些方法可以使用python和oauth2.0导入谷歌联系人?

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

所以像:

 from apiclient.discover import build
 import httplib2
 http = httplib2.Http()
 #Authorization
 service = build("contacts", "v3", http=http) 
Run Code Online (Sandbox Code Playgroud)

给我们UnknownApiNameOrVersion例外.看起来联系人API不在apiclient支持的API列表中.

我正在寻找替代方法.

bos*_*ter 21

谷歌联系人API不能与使用google-api-python-client库,因为它是谷歌数据API,而google-api-python-client旨在与使用基于查询的API.

您可以使用对OAuth 2.0的原生支持,而不是经历@NikolayFominyh所描述的所有麻烦gdata-python-client.

要获取有效令牌,请按照Google Developers 博客文章中的说明操作,以获得有关此过程的详细说明.

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

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)
Run Code Online (Sandbox Code Playgroud)

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

APPLICATION_REDIRECT_URI = 'http://www.example.com/oauth2callback'
authorize_url = auth_token.generate_authorize_url(
    redirect_uri=APPLICATION_REDIRECT_URI)
Run Code Online (Sandbox Code Playgroud)

生成此内容后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)
Run Code Online (Sandbox Code Playgroud)

在您访问浏览器的情况下,您需要将重定向到的URL复制到变量中redirect_url.

如果您在Web应用程序中,您将能够指定路径的处理程序/oauth2callback(例如),并且只需检索查询参数code即可交换令牌的代码.例如,如果使用WebOb:

redirect_url = atom.http_core.Uri.parse_uri(self.request.uri)
Run Code Online (Sandbox Code Playgroud)

最后使用此令牌授权您的客户:

import gdata.contacts.service

client = gdata.contacts.service.ContactsService(source='appname')
auth_token.authorize(client)
Run Code Online (Sandbox Code Playgroud)

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

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