Last time it was CLI, so this time it's a web application
reference https://developers.google.com/api-client-library/python/auth/web-app
Credentials require authentication of approved redirect URL
Download JSON data after creation
sample I'm using django, so I use HttpResponse Redirect
from oauth2client import client
from django.http import HttpResponseRedirect
flow = client.flow_from_clientsecrets(
'client_secrets.json',
scope='https://www.googleapis.com/auth/drive.metadata.readonly',
redirect_uri='http://www.example.com/oauth2callback')
auth_uri = flow.step1_get_authorize_url()
return HttpResponseRedirect(auth_uri)
Account authentication is performed, so select any account
Since the authentication code can be obtained with the approved redirect URL, use it to obtain analytics data.
auth_code = request.GET['code']
flow = client.flow_from_clientsecrets(
'client_secrets.json',
scope='https://www.googleapis.com/auth/drive.metadata.readonly',
redirect_uri='http://www.example.com/oauth2callback')
credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())
analytics = build('analytics', 'v4', http=http_auth, discoveryServiceUrl=self.DISCOVERY_URI)
reports = analytics.reports()
reports.batchGet(
body={
'reportRequests': [
{
'viewId': self.VIEW_ID,
'dateRanges': [{'startDate': self.target_date, 'endDate': 'today'}],
"dimensions": [
{
"name": "ga:productSku", #The product code of the item sold.
}],
'metrics': [
{'expression': 'ga:itemQuantity'} #The number of items sold in an e-commerce transaction.
],
'pageSize': 50000,
'pageToken': "nextpage",
"orderBys":
[
{"fieldName": "ga:itemQuantity", "sortOrder": "DESCENDING"},
]
}]
}
).execute()
Recommended Posts