Подключение к Google Analytics API с помощью Python

Я пытался следовать этому руководству, чтобы подключиться к Google Analytics API. Я следовал инструкциям, шаг за шагом. У меня на компьютере установлен Python 2.7. Я установил клиентскую библиотеку Google. Когда я запускаю программу, я получаю в терминале следующую ошибку:

Traceback (most recent call last):
  File "HelloAnalytics.py", line 6, in <module>
    from oauth2client.client import SignedJwtAssertionCredential
ImportError: cannot import name SignedJwtAssertionCredentials

Строка 6, к которой он относится:

from oauth2client.client import SignedJwtAssertionCredentials

Я совершенно потерялся. Я посмотрел на других, у которых была такая же ошибка, здесь, здесь и здесь, но решения не сработали. У меня есть некоторые познания в программировании, но по сравнению со многими из вас я новичок.

Полный код здесь:

"""A simple example of how to access the Google Analytics API."""

import argparse

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools



def get_service(api_name, api_version, scope, key_file_location,
                service_account_email):
  """Get a service that communicates to a Google API.

  Args:
    api_name: The name of the api to connect to.
    api_version: The api version to connect to.
    scope: A list auth scopes to authorize for the application.
    key_file_location: The path to a valid service account p12 key file.
    service_account_email: The service account email address.

  Returns:
    A service that is connected to the specified API.
  """

  f = open(key_file_location, 'rb')
  key = f.read()
  f.close()

  credentials = SignedJwtAssertionCredentials(service_account_email, key,
    scope=scope)

  http = credentials.authorize(httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service


def get_first_profile_id(service):
  # Use the Analytics service object to get the first profile id.

  # Get a list of all Google Analytics accounts for this user
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    # Get the first Google Analytics account.
    account = accounts.get('items')[0].get('id')

    # Get a list of all the properties for the first account.
    properties = service.management().webproperties().list(
        accountId=account).execute()

    if properties.get('items'):
      # Get the first property id.
      property = properties.get('items')[0].get('id')

      # Get a list of all views (profiles) for the first property.
      profiles = service.management().profiles().list(
          accountId=account,
          webPropertyId=property).execute()

      if profiles.get('items'):
        # return the first view (profile) id.
        return profiles.get('items')[0].get('id')

  return None


def get_results(service, profile_id):
  # Use the Analytics Service Object to query the Core Reporting API
  # for the number of sessions within the past seven days.
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='7daysAgo',
      end_date='today',
      metrics='ga:sessions').execute()


def print_results(results):
  # Print data nicely for the user.
  if results:
    print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
    print 'Total Sessions: %s' % results.get('rows')[0][0]

  else:
    print 'No results found'


def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.readonly']

  # Use the developer console and replace the values with your
  # service account email and relative location of your key file.
  service_account_email = '<Replace with your service account email address.>'
  key_file_location = '<Replace with /path/to/generated/client_secrets.p12>'

  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, key_file_location,
    service_account_email)
  profile = get_first_profile_id(service)
  print_results(get_results(service, profile))


if __name__ == '__main__':
  main()

Любая помощь или направление будут оценены.


person Jay    schedule 02.03.2016    source источник


Ответы (1)


исходный репозиторий был недавно обновлен, а Hello Analytics Guides также были обновлены, чтобы использовать новый код:

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

...
credentials = ServiceAccountCredentials.from_p12_keyfile(
    service_account_email, key_file_location, scopes=scope)

Где service_account_email - это адрес электронной почты учетной записи службы, которую вы получаете из консоли разработчика, а key_file_locaiton - это /the/path/to/key.p12, а scopes - это scopes, которые необходимо предоставить учетной записи службы.

Не забудьте добавить адрес электронной почты сервисного аккаунта в качестве авторизованного пользователя представления (профиля) Google Analytics, к которому вы хотите, чтобы у него был доступ.

person Matt    schedule 03.03.2016
comment
Здравствуйте, спасибо за обновление. Но теперь я получаю эту ошибку: TypeError: аргумент file () 1 должен быть закодированной строкой без байтов NULL, а не str - person Jay; 03.03.2016
comment
Отслеживание (последний вызов последним): Файл C: \ Users \ me \ Desktop \ Новая папка (3) \ HelloAnalytics.py, строка 112, в ‹module› main () Файл C: \ Users \ u6023273 \ Desktop \ Новая папка (3) \ HelloAnalytics.py, строка 106, в основном service_account_email) Файл C: \ Users \ me \ Desktop \ New folder (3) \ HelloAnalytics.py, строка 35, в get_service service_account_email, key, scopes = scope) - person Jay; 03.03.2016
comment
Файл C: \ Python27 \ lib \ site-packages \ oauth2client \ service_account.py, строка 272, в from_p12_keyfile с open (filename, 'rb') как file_obj: TypeError: аргумент file () 1 должен быть закодированной строкой без байтов NULL, не ул - person Jay; 03.03.2016
comment
В образце была ошибка, которую с тех пор исправили. Вам нужно удалить часть, которая читает файл. Новый вызов - это просто `credentials = ServiceAccountCredentials.from_p12_keyfile (service_account_email, key_file_location, scopes = scope)`, где key_file_locaiton - это просто имя файла. - person Matt; 12.03.2016