我正在尝试使用python HelloAnalytics.py
代码运行Google Analytics Reporting API,但遇到以下问题。
Traceback (most recent call last):
File "/Users/Documents/myGitProjects/GoogleAnalytics/src/googleapi_test.py", line 4, in <module>
from oauth2client.service_account import ServiceAccountCredentials
File "/Users/Library/Python/3.7/lib/python/site-packages/oauth2client/service_account.py", line 42, in <module>
class ServiceAccountCredentials(client.AssertionCredentials):
File "/Users/Library/Python/3.7/lib/python/site-packages/oauth2client/service_account.py", line 86, in ServiceAccountCredentials
client.AssertionCredentials.NON_SERIALIZED_MEMBERS)
TypeError: unsupported operand type(s) for |: 'frozenset' and 'list'
我按照教程中给出的分步说明进行操作(链接复制如下),以访问Analytics Reporting API v4。
{{3}}
我不确定,我在做什么错。对于解决此问题的一些帮助将不胜感激。
这是我的代码。
from googleapiclient import *
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = './google_analytics_e8d32ff64078.json'
VIEW_ID = '63259616'
def initialize_analyticsreporting():
"""Initializes an Analytics Reporting API V4 service object.
Returns:
An authorized Analytics Reporting API V4 service object.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
# Build the service object.
analytics = build('analyticsreporting', 'v4', credentials=credentials)
return analytics
def get_report(analytics):
"""Queries the Analytics Reporting API V4.
Args:
analytics: An authorized Analytics Reporting API V4 service object.
Returns:
The Analytics Reporting API V4 response.
"""
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:sessions'}],
'dimensions': [{'name': 'ga:country'}]
}]
}
).execute()
def print_response(response):
"""Parses and prints the Analytics Reporting API V4 response.
Args:
response: An 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', [])
for row in report.get('data', {}).get('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()
谢谢。