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

时间:2016-03-08 13:48:51

标签: python google-app-engine flask gdata google-app-engine-python

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

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

来自doc:

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 - 未经授权"您的请求中有错误。这就是我们所知道的所有"

create_contact来自doc

1 个答案:

答案 0 :(得分:1)

使用示例@dyerad指示并在Google Contacts API doc创建联系人的spinet我创建了下面的示例代码。

我只需要修复我从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)