如何在 python 中授权 gdata 联系人客户端

How to authorise a gdata contacts client in python

我正在尝试使用 Google 联系人 API 向用户的联系人添加条目。 我已经设法使用 OAuth2 并获得访问令牌并向 Google 联系人 API 发出授权请求。但我是手动完成的,一个简单的 GET 到 https://www.google.com/m8/feeds/contacts/default/full。 我想使用 gdata 所以我不必手动创建 xml.

问题是我无法授权 gdata 的 ContactsClient。

来自文档:

gd_client = gdata.contacts.client.ContactsClient(source='YOUR_APPLICATION_NAME')
# Authorize the client.

但是如何授权呢? example 使用电子邮件和密码创建授权的 ContactsClient

self.gd_client = gdata.contacts.client.ContactsClient(source='GoogleInc-ContactsPythonSample-1')
self.gd_client.ClientLogin(email, password, self.gd_client.source)

而目前我还没有找到如何授权gdata客户端。 我确实发现我可以将 gdata.gauth.ClientLoginToken 传递给 gdata.contacts.client.ContactsClient,但效果不佳

auth_token = gdata.gauth.ClientLoginToken(credentials.access_token)
gd_client = gdata.contacts.client.ContactsClient(
     source='project-id',
     auth_token=auth_token)
contact = create_contact(gd_client)

我收到 401 - 未授权 "There was an error in your request. That's all we know"

这个create_contact来自doc

使用示例@dyerad 指示和尖晶石在 Google Contacts API doc 上创建联系人我创建了下面的示例代码。

我只需要修复从 doc 中提取的 create_contact 片段中的一个小错误。你应该使用

    # Set the contact's postal address.
    new_contact.structured_postal_address.append(gdata.data.StructuredPostalAddress(
        rel=gdata.data.WORK_REL, primary='true',
        street=gdata.data.Street(text='1600 Amphitheatre Pkwy'),
        city=gdata.data.City(text='Mountain View'),
        region=gdata.data.Region(text='CA'),
        postcode=gdata.data.Postcode(text='94043'),
        country=gdata.data.Country(text='United States')))

而不是

# Set the contact's postal address.
new_contact.structured_postal_address.append(
  rel=gdata.data.WORK_REL, primary='true',
  street=gdata.data.Street(text='1600 Amphitheatre Pkwy'),
  city=gdata.data.City(text='Mountain View'),
  region=gdata.data.Region(text='CA'),
  postcode=gdata.data.Postcode(text='94043'),
  country=gdata.data.Country(text='United States'))

完整代码如下:

import flask
import httplib2
from oauth2client import client
from logging import info as linfo
import atom.data
import gdata.gauth
import gdata.data
import gdata.contacts.client
import gdata.contacts.data

app = flask.Flask(__name__)

client_info = {
    "client_id": "<CLIENT_ID>",
    "client_secret": "<CONTACTS_CLIENT_SECRET>",
    "redirect_uris": [],
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token"
}

scopes = 'https://www.google.com/m8/feeds/'


def create_contact(gd_client):
    new_contact = gdata.contacts.data.ContactEntry()
    # Set the contact's name.
    new_contact.name = gdata.data.Name(
        given_name=gdata.data.GivenName(text='Elizabeth'),
        family_name=gdata.data.FamilyName(text='Bennet'),
        full_name=gdata.data.FullName(text='Elizabeth Bennet'))
    new_contact.content = atom.data.Content(text='Notes')
    # Set the contact's email addresses.
    new_contact.email.append(gdata.data.Email(address='liz@gmail.com',
                                              primary='true',
                                              rel=gdata.data.WORK_REL,
                                              display_name='E. Bennet'))
    new_contact.email.append(gdata.data.Email(address='liz@example.com',
                                              rel=gdata.data.HOME_REL))
    # Set the contact's phone numbers.
    new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1212',
                                                           rel=gdata.data.WORK_REL,
                                                           primary='true'))
    new_contact.phone_number.append(gdata.data.PhoneNumber(text='(206)555-1213',
                                                           rel=gdata.data.HOME_REL))
    # Set the contact's IM address.
    new_contact.im.append(gdata.data.Im(address='liz@gmail.com',
                                        primary='true', rel=gdata.data.HOME_REL,
                                        protocol=gdata.data.GOOGLE_TALK_PROTOCOL))
    # Set the contact's postal address.
    new_contact.structured_postal_address.append(gdata.data.StructuredPostalAddress(
        rel=gdata.data.WORK_REL, primary='true',
        street=gdata.data.Street(text='1600 Amphitheatre Pkwy'),
        city=gdata.data.City(text='Mountain View'),
        region=gdata.data.Region(text='CA'),
        postcode=gdata.data.Postcode(text='94043'),
        country=gdata.data.Country(text='United States')))
    # Send the contact data to the server.
    contact_entry = gd_client.CreateContact(new_contact)
    linfo('Contact\'s ID: %s' % contact_entry.id.text)
    return contact_entry


@app.route('/gdata/oauth')
def gdata_oauth():
    request_token = gdata.gauth.OAuth2Token(
        client_id=client_info['client_id'],
        client_secret=client_info['client_secret'],
        scope=scopes,
        user_agent=None)

    return flask.redirect(
        request_token.generate_authorize_url(
            redirect_uri=flask.url_for('gdata_oauth2callback', _external=True)))


@app.route('/gdata/oauth2callback')
def gdata_oauth2callback():
    if 'error' in flask.request.args:
        return str(flask.request.args.get('error'))
    elif 'code' not in flask.request.args:
        return flask.redirect(flask.url_for('gdata_oauth'))
    else:
        request_token = gdata.gauth.OAuth2Token(
            client_id=client_info['client_id'],
            client_secret=client_info['client_secret'],
            scope=scopes,
            user_agent=None)
        request_token.redirect_uri =\
            flask.url_for('gdata_oauth2callback', _external=True)
        request_token.get_access_token(flask.request.args.get('code'))
        gd_client = gdata.contacts.client.ContactsClient(
            source='project-id',
            auth_token=request_token)
        contact = create_contact(gd_client)
        return str(contact)