简体   繁体   English

python:IOError:[Errno 13]权限被拒绝。 当我尝试使用google-analytics-api示例代码时

[英]python:IOError: [Errno 13] Permission denied. When I tried google-analytics-api sample code

I am trying to get data from google-analytics-api, I run the sample code:HelloAnalytics.py( https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py ), but there are some error:IOError: [Errno 13] I had added my service account email address to my GA account I am using mac os. 我正在尝试从google-analytics-api获取数据,我运行了示例代码:HelloAnalytics.py( https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py ),但是有一些错误:IOError:[Errno 13]我已将服务帐户电子邮件地址添加到我正在使用mac os的GA帐户中。

detail error message: 详细错误消息:

   Traceback (most recent call last):
  File "/Users/mac/Documents/python-f/HelloAnalytics.py", line 82, in <module>
    main()
  File "/Users/mac/Documents/python-f/HelloAnalytics.py", line 77, in main
    analytics = initialize_analyticsreporting()
  File "/Users/mac/Documents/python-f/HelloAnalytics.py", line 34, in initialize_analyticsreporting
    analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)
  File "build/bdist.macosx-10.12-intel/egg/oauth2client/_helpers.py", line 133, in positional_wrapper
  File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 222, in build
  File "build/bdist.macosx-10.12-intel/egg/googleapiclient/discovery.py", line 269, in _retrieve_discovery_doc
  File "build/bdist.macosx-10.12-intel/egg/oauth2client/transport.py", line 159, in new_request
  File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 744, in _refresh
  File "build/bdist.macosx-10.12-intel/egg/oauth2client/client.py", line 775, in _do_refresh_request
  File "build/bdist.macosx-10.12-intel/egg/oauth2client/transport.py", line 282, in request
  File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1609, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1351, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1272, in _conn_request
    conn.connect()
  File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 1036, in connect
    self.disable_ssl_certificate_validation, self.ca_certs)
  File "/Library/Python/2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/__init__.py", line 80, in _ssl_wrap_socket
    cert_reqs=cert_reqs, ca_certs=ca_certs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 911, in wrap_socket
    ciphers=ciphers)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 520, in __init__
    self._context.load_verify_locations(ca_certs)
IOError: [Errno 13] Permission denied

the source code: 源代码:

"""Hello Analytics Reporting API V4."""

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


SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')
KEY_FILE_LOCATION = '/Users/mac/Documents/python-f/MyProject-a7c00ebc9685.p12'
SERVICE_ACCOUNT_EMAIL = 'data-510@prime-imagery-150409.iam.gserviceaccount.com'
VIEW_ID = '120100451'


def initialize_analyticsreporting():
  """Initializes an analyticsreporting service object.

  Returns:
    analytics an authorized analyticsreporting service object.
  """

  credentials = ServiceAccountCredentials.from_p12_keyfile(
    SERVICE_ACCOUNT_EMAIL, KEY_FILE_LOCATION, scopes=SCOPES)

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

  # Build the service object.
  analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)

  return analytics


def get_report(analytics):
  # Use the Analytics Service Object to query the Analytics Reporting API V4.
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}]
        }]
      }
  ).execute()


def print_response(response):
  """Parses and prints the Analytics Reporting API V4 response"""

  for report in response.get('reports', []):
    columnHeader = report.get('columnHeader', {})
    dimensionHeaders = columnHeader.get('dimensions', [])
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
    rows = report.get('data', {}).get('rows', [])

    for row in rows:
      dimensions = row.get('dimensions', [])
      dateRangeValues = row.get('metrics', [])

      for header, dimension in zip(dimensionHeaders, dimensions):
        print header + ': ' + dimension

      for i, values in enumerate(dateRangeValues):
        print 'Date range (' + str(i) + ')'
        for metricHeader, value in zip(metricHeaders, values.get('values')):
          print metricHeader.get('name') + ': ' + value


def main():

  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  print_response(response)

if __name__ == '__main__':
  main()

You are using a service account. 您正在使用服务帐户。 Did you give the service account access to your Google Analytics account? 您是否授予服务帐户访问您的Google Analytics(分析)帐户的权限?

Go to the google analytics website under admin add the service account email address at the ACCOUNT level to the account you wish to request data for. 转到“管理员”下的Google Analytics(分析)网站,将ACCOUNT级别的服务帐户电子邮件地址添加到您要为其请求数据的帐户中。

Idea number two: 想法二:

IOError: [Errno 13] Permission denied check that you have permssions to the p12 file. IOError: [Errno 13] Permission denied请检查您是否对p12文件具有IOError: [Errno 13] Permission denied

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM