python - TypeError : file() argument 1 must be encoded string without NULL bytes, 不是 str

标签 python google-analytics google-analytics-api

我正在尝试关注 this tutorial to so connect to Google Analytics API .我一步一步地跟着一切。但是当我在 python 中运行模块时,出现以下错误:

Traceback (most recent call last):
  File "C:\Users\me\Desktop\New folder (3)\HelloAnalytics.py", line 112, in <module>
    main()
  File "C:\Users\me\Desktop\New folder (3)\HelloAnalytics.py", line 106, in main
    service_account_email)
  File "C:\Users\me\Desktop\New folder (3)\HelloAnalytics.py", line 35, in get_service
    service_account_email, key, scopes=scope)
  File "C:\Python27\lib\site-packages\oauth2client\service_account.py", line 274, in from_p12_keyfile
    with open(filename, 'rb') as file_obj:
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

如果有人能指出我正确的方向,那就太好了。完整代码就在这里:

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

import argparse

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

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 = ServiceAccountCredentials.from_p12_keyfile(
    service_account_email, key, scopes=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()

最佳答案

错误被追溯到ServiceAccountCredentials.from_p12_keyfile()功能。它似乎在 service_account_email 字符串中检测到空值。您可以通过在第一个引号前加上“r”使其成为原始字符串:

service_account_email = r'<Replace with your service account email address.>'

或使用反斜杠“\”转义空值。

关于python - TypeError : file() argument 1 must be encoded string without NULL bytes, 不是 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35806481/

相关文章:

python - 我收到 "AttributeError: module ' Discord.ext.commands' has no attribute 'bot"错误

javascript - 在单独的 .js 文件中使用谷歌分析的代码是什么?

php - 谷歌分析API用户登录总是需要登录

python - Scipy ODR python

javascript - 如何使用 Zapier 的 Twitter API 进行身份验证?

javascript - Google 跟踪代码管理器 - 设置后立即读取 cookie

python - 谷歌分析报告 API v4 : nextPagetoken cannot go beyond 10, 000 行(Python)

python - 在 Pandas Dataframe 上迭代 Google 分析 API 函数

Python [Errno 98] 地址已在使用中

php - Google_Service_AnalyticsReporting_DimensionFilterClause中的多个过滤器