-
Notifications
You must be signed in to change notification settings - Fork 0
/
analytics.py
executable file
·54 lines (41 loc) · 1.36 KB
/
analytics.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
#!/usr/bin/env python
import random
import uuid
# cannot use tornado.httpclient.AsyncHTTPClient (see http://git.io/EUDgzw)
import requests
class Analytics:
def __init__(self, tracking_id):
assert tracking_id.startswith('UA-')
self.tracking_id = tracking_id
def report_pageview(self, uri,
referer=None, user_ip=None, user_agent=None):
rand = str(random.randrange(1 << 128))
rand_uuid = str(uuid.uuid4()) # random uuid
payload = {
'v': '1',
'z': rand, # cache buster
'cid': rand_uuid, # treat every hit as an independent one
'tid': self.tracking_id,
'aip': '1', # anonymize IP
'dp': uri,
'uip': '127.0.0.1' # default
}
if referer:
payload['dr'] = referer
if user_ip:
payload['uip'] = user_ip
if user_agent:
payload['ua'] = user_agent
try:
resp = requests.post('https://ssl.google-analytics.com/collect',
data=payload, verify=False)
except Exception:
# Do nothing
return 403
return resp.status_code
def main():
from config import ANALYTICS_ID
analytics = Analytics(ANALYTICS_ID)
analytics.report_pageview('/test')
if __name__ == '__main__':
main()