【问题标题】:Connecting to Google Analytics API using Python使用 Python 连接到 Google Analytics API
【发布时间】:2016-06-15 21:07:23
【问题描述】:

我已尝试关注 this tutorial 以连接到 Google Analytics API。我已按照说明一步一步地进行操作。我的电脑上安装了 Python 2.7。我已经安装了谷歌客户端库。当我运行程序时,我在终端中收到以下错误:

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

我完全迷路了。我查看了其他有相同错误的人hereherehere,但解决方案不起作用。我有一些编程知识,但与你们中的许多人相比,我是一个菜鸟。

完整代码在这里:

"""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()

任何帮助或指导将不胜感激。

【问题讨论】:

    标签: python api google-analytics google-analytics-api


    【解决方案1】:

    source repository 最近已更新,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.p12scopes 是您需要授予服务帐户的scopes

    请记住将服务帐户电子邮件地址添加为您希望其访问的 Google Analytics(分析)数据视图(配置文件)的授权用户。

    【讨论】:

    • 您好,感谢您的更新。但是现在我得到了这个错误: TypeError: file() argument 1 must be encrypted string without NULL bytes, not str
    • Traceback(最近一次调用最后):文件“C:\Users\me\Desktop\New 文件夹 (3)\HelloAnalytics.py”,第 112 行,在 main() 文件中“ C:\Users\u6023273\Desktop\New 文件夹 (3)\HelloAnalytics.py",第 106 行,在主 service_account_email) 文件 "C:\Users\me\Desktop\New 文件夹 (3)\HelloAnalytics.py",行35、在get_service service_account_email, key, scopes=scope)
    • 文件“C:\Python27\lib\site-packages\oauth2client\service_account.py”,第 272 行,在 from_p12_keyfile 中,open(filename, 'rb') as file_obj: TypeError: file()参数 1 必须是没有 NULL 字节的编码字符串,而不是 str
    • 样本中存在错误,现已更正。您需要删除读取文件的部分。新的调用只是 `credentials = ServiceAccountCredentials.from_p12_keyfile(service_account_email, key_file_location, scopes=scope)` 其中 key_file_locaiton 只是文件名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多