Referenz https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/installed-py
Beispielklasse
class GoogleAnalyticsUtility(object):
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')
VIEW_ID = 'xxxx'
def __init__(self, target_date):
self.target_date = target_date
def get_report(self):
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[tools.argparser])
flags = parser.parse_args(['--noauth_local_webserver'])
CLIENT_SECRETS_PATH = os.path.join(settings.BASE_DIR, '../etc/googleapi/client_id.json')
flow = client.flow_from_clientsecrets(
CLIENT_SECRETS_PATH, scope=self.SCOPES,
message=tools.message_if_missing(CLIENT_SECRETS_PATH))
storage = file.Storage(os.path.join(settings.BASE_DIR, '../etc/googleapi/analyticsreporting.dat'))
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())
analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=self.DISCOVERY_URI)
reports = analytics.reports()
return reports.batchGet(
body={
'reportRequests': [
{
'viewId': self.VIEW_ID,
'dateRanges': [{'startDate': self.target_date, 'endDate': 'today'}],
"dimensions": [
{
"name": "ga:productSku", #Der Produktcode des verkauften Artikels.
}],
'metrics': [
{'expression': 'ga:itemQuantity'} #Die Anzahl der Artikel, die in einer E-Commerce-Transaktion verkauft wurden.
],
'pageSize': 50000,
'pageToken': "nextpage",
"orderBys":
[
{"fieldName": "ga:itemQuantity", "sortOrder": "DESCENDING"},
]
}]
}
).execute()
target_date = date.today() - timedelta(days=7)
ga = GoogleAnalyticsUtility(target_date.strftime('%Y-%m-%d'))
ga.get_report()
Wenn Sie in der Befehlszeile darauf klicken, wird ein Link angezeigt. Kopieren Sie ihn und fügen Sie ihn in den Browser ein, um die Authentifizierung abzuschließen
https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&response_type=code&client_id=xxxxx-gd5j31ge4jdobhlg9a3jqnveae34cag1.apps.googleusercontent.com&access_type=offline
Recommended Posts