-
Notifications
You must be signed in to change notification settings - Fork 0
/
ga4.py
141 lines (117 loc) · 4.67 KB
/
ga4.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import traceback
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Filter,
FilterExpression,
Metric,
OrderBy,
RunReportRequest,
)
TTL = 1 * 60 * 60
def cache(ttl=None):
dummy = object()
cache = {}
def wrapper(fn):
def inner_wrapper(*args, **kwargs):
# TODO: include arguments in the key
# key = fn.__qualname__ + args + kwargs
key = fn.__qualname__
# cache hit?
if key in cache:
value, time = cache[key]
# ttl valid?
if (time + timedelta(seconds=ttl)) < datetime.now():
value = dummy
else:
value = dummy
if value is dummy:
value = fn(*args, **kwargs)
cache[key] = (value, datetime.now())
return value
return inner_wrapper
return wrapper
class GoogleAnalyticsMetrics:
def __init__(self, property_id, credentials_path):
self.property_id = property_id
self.client = BetaAnalyticsDataClient.from_service_account_json(credentials_path)
def _run_report(self, **kwargs):
try:
request = RunReportRequest(property=f"properties/{self.property_id}", **kwargs)
response = self.client.run_report(request)
except Exception as e:
traceback.print_exc()
return {
"dimensions": [],
"metrics": [],
}
return {
"dimensions": [row.dimension_values[0].value for row in response.rows],
"metrics": [row.metric_values[0].value for row in response.rows],
}
@cache(ttl=TTL)
def get_pageviews(self):
now = datetime.now()
end_date = now - timedelta(days=now.day)
start_date = now - relativedelta(months=6, days=now.day - 1)
return self._run_report(
metrics=[Metric(name="sessions")],
dimensions=[Dimension(name="yearMonth")],
date_ranges=[DateRange(start_date=start_date.strftime("%Y-%m-%d"), end_date=end_date.strftime("%Y-%m-%d"))],
order_bys=[OrderBy(dimension=OrderBy.DimensionOrderBy(dimension_name="yearMonth"), desc=False)],
)
@cache(ttl=TTL)
def get_top_pages(self):
return self._run_report(
metrics=[Metric(name="sessions")],
dimensions=[Dimension(name="pagePath")],
date_ranges=[DateRange(start_date="90daysAgo", end_date="yesterday")],
order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
dimension_filter=FilterExpression(
not_expression=FilterExpression(
filter=Filter(
field_name="pagePath",
string_filter=Filter.StringFilter(match_type=Filter.StringFilter.MatchType.EXACT, value="/"),
),
)
),
limit=15,
)
@cache(ttl=TTL)
def get_acquisition(self):
return self._run_report(
metrics=[Metric(name="sessions")],
dimensions=[Dimension(name="sessionDefaultChannelGroup")],
date_ranges=[DateRange(start_date="90daysAgo", end_date="yesterday")],
order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
)
@cache(ttl=TTL)
def get_top_contries(self):
return self._run_report(
metrics=[Metric(name="sessions")],
dimensions=[Dimension(name="country")],
date_ranges=[DateRange(start_date="90daysAgo", end_date="yesterday")],
order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
limit=10,
)
@cache(ttl=TTL)
def get_top_oses(self):
return self._run_report(
metrics=[Metric(name="sessions")],
dimensions=[Dimension(name="operatingSystem")],
date_ranges=[DateRange(start_date="90daysAgo", end_date="yesterday")],
order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
limit=10,
)
@cache(ttl=TTL)
def get_top_browsers(self):
return self._run_report(
metrics=[Metric(name="sessions")],
dimensions=[Dimension(name="browser")],
date_ranges=[DateRange(start_date="90daysAgo", end_date="yesterday")],
order_bys=[OrderBy(metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True)],
limit=10,
)