-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsessionNumbersLast30.py
More file actions
78 lines (57 loc) · 2.08 KB
/
Copy pathsessionNumbersLast30.py
File metadata and controls
78 lines (57 loc) · 2.08 KB
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
"""Hello Analytics Reporting API V4."""
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import json
from datetime import datetime
from datetime import timedelta
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = ''
VIEW_ID = ''
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': '30daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:sessions'}],
'dimensions': [{'name': 'ga:nthDay'}]
}]
}
).execute()
# Google Analytics returns nthDay with leading 0's, get rid of them
# here and convert to date stamps
def ConvertDays(r):
for iRow in range(len(r["reports"][0]["data"]["rows"])):
day = r["reports"][0]["data"]["rows"][iRow]["dimensions"][0]
day = int(day)
day = datetime.strftime(datetime.now() - timedelta(days= 30 - day), '%d %b %Y 06:00:00')
#print r["reports"][0]["data"]["rows"][iRow]["dimensions"][0] + " = " + day
r["reports"][0]["data"]["rows"][iRow]["dimensions"][0] = day
return r
# use json.dumps to dump output, this should be the only
# thing that prints when logstash runs the code
def main():
analytics = initialize_analyticsreporting()
response = get_report(analytics)
response = ConvertDays(response)
print json.dumps(response)
return response
if __name__ == '__main__':
main()