Как авторизовать клиент gdata без использования рабочего процесса gdata oauth2?

У меня уже есть access_token и refresh_token, но я не могу найти способ создания авторизованного клиента gdata без прохождения всего рабочего процесса генерации токенов в gdata.

3 ответа

Решение

Так что я наконец-то заработал. Вот как я это сделал:

    client = gdata.contacts.client.ContactsClient()
    credentials = gdata.gauth.OAuth2Token(client_id = 'client_id',
                                          client_secret = 'client_secret',
                                          scope = 'https://www.google.com/m8/feeds/',
                                          user_agent = auth.user_agent, # This is from the headers sent to google when getting your access token (they don't return it)
                                          access_token = auth.access_token,
                                          refresh_token = auth.refresh_token)

    credentials.authorize(client)
    contacts = client.get_contacts()

Попробуй это:

import httplib2
from oauth2client.client import OAuth2Credentials

credentials = OAuth2Credentials('access_token', client_id, client_secret, 'refresh_token', 'token_expiry','token_uri','user_agent')
# the client_id and client_secret are the ones that you receive which registering the App 
# and the token_uri is the Redirect url you register with Google for handling the oauth redirection
# the token_expiry and the user_agent is the one that you receive when exchange the code for access_token
http = httplib2.Http()
http = credentials.authorize(http)
service = build('analytics', 'v3', http=http) # this will give you the service object which you can use for firing API calls

Gdata позволяет вам аутентифицироваться, используя информацию о пользователе, напр. имя пользователя / пароль... вот фрагмент кода из файла api /gdata-2.0.18/samples/docs/docs_example.py из Python gdata, который поставляется вместе с API

class DocsSample(object): """Объект DocsSample демонстрирует фид списка документов." ""

def init(self, email, password): "" "Конструктор для объекта DocsSample.

Takes an email and password corresponding to a gmail account to
demonstrate the functionality of the Document List feed.

Args:
  email: [string] The e-mail address of the account to use for the sample.
  password: [string] The password corresponding to the account specified by
      the email parameter.

Returns:
  A DocsSample object used to run the sample demonstrating the
  functionality of the Document List feed.
"""
source = 'Document List Python Sample'
self.gd_client = gdata.docs.service.DocsService()
self.gd_client.ClientLogin(email, password, source=source)

# Setup a spreadsheets service for downloading spreadsheets
self.gs_client = gdata.spreadsheet.service.SpreadsheetsService()
self.gs_client.ClientLogin(email, password, source=source)

если вы вызываете его как {python ./docs_example.py --user username --pw password}, ​​он пропустит запрос об этом, но, если вы этого не сделаете, попросит вас об этом. Однако это считается устаревшим, но все же работает в большинстве ситуаций вне сетей, которые напрямую работают с Google, так как теперь это часто требует oauth2. При этом у него есть недостатки безопасности, в частности, область применения и плохая защита паролем, поэтому его не рекомендуют... но это должно немного лучше ответить на ваш вопрос...

Другие вопросы по тегам