-
Notifications
You must be signed in to change notification settings - Fork 0
/
ga_requests.py
80 lines (52 loc) · 2.09 KB
/
ga_requests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
import pandas as pd
#Google Analytics API v4
"""
Input filepath when instantiating class
Input view id when instantiating class
"""
class GA_Reporting:
def __init__(self, OAuth, view_number):
self.credentials_file = OAuth
self.view = view_number
#report request framework
self.body = \
{
'reportRequests': [
{
'viewId': self.view,
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:sessions'}],
'dimensions': [{'name': 'ga:country'}]
}
]
}
def initialize_analyticsreporting_v2(self):
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
#remeber to use the json generated when you create the service account credentials.
KEY_FILE_LOCATION = self.credentials_file
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
# Build the service object.
analytics = build('analytics', 'v4', credentials=credentials)
return analytics
#modifying report requests
def mod_date(self):
self.start_date = raw_input("enter a start date: ")
#add a function to ensure proper date format
self.end_date = raw_input("enter a end date: ")
#add a function to ensure proper date format
for report in self.body['reportRequests']:
report['dateRanges'][0]["startDate"] = self.start_date
report['dateRanges'][0]["endDate"] = self.end_date
#requesting reports
def get_report(self):
#generate authentication
analytics = self.initialize_analyticsreporting_v2()
return analytics.reports().batchGet(self.body).execute()
#formatting reports into pandas dataframes