-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathweb-visits-data-analytics-javascript-python--geoip.html
More file actions
203 lines (155 loc) · 7.2 KB
/
web-visits-data-analytics-javascript-python--geoip.html
File metadata and controls
203 lines (155 loc) · 7.2 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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
<!DOCTYPE html>
<html lang="en" itemscope itemtype="http://schema.org/Article">
<head>
<title>Getting web visits data for analytics with Javascript, Python and GeoIP</title>
<meta charset="utf-8">
<meta property="og:title" content="Getting web visits data for analytics with Javascript, Python and GeoIP">
<meta property="og:site_name" content="Modesto Mas | Blog">
<meta property="og:image" content="https://mmas.github.io/images/profile.jpg">
<meta property="og:image:width" content="200">
<meta property="og:image:height" content="200">
<meta property="og:url" content="https://mmas.github.io/web-visits-data-analytics-javascript-python--geoip">
<meta property="og:locale" content="en_GB">
<meta name="twitter:image" content="https://mmas.github.io/images/profile.jpg">
<meta name="twitter:url" content="https://mmas.github.io/web-visits-data-analytics-javascript-python--geoip">
<meta name="twitter:card" content="summary">
<meta name="twitter:domain" content="mmas.github.io">
<meta name="twitter:title" content="Getting web visits data for analytics with Javascript, Python and GeoIP">
<meta name="description" content="Requirements % apt-get install -y geoip-database % pip install python-dateutil pygeoip Browser data We are going to parse the navigator data to obtain...">
<meta name="twitter:description" content="Requirements % apt-get install -y geoip-database % pip install python-dateutil pygeoip Browser data We are going to parse the navigator data to obtain...">
<meta property="og:description" content="Requirements % apt-get install -y geoip-database % pip install python-dateutil pygeoip Browser data We are going to parse the navigator data to obtain...">
<meta name="keywords" content="data-processing,geoip,javascript,python,web-analytics">
<meta property="og:type" content="blog">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:type" content="article">
<meta property="article:author" content="https://github.com/mmas">
<meta property="article:section" content="data-processing">
<meta property="article:tag" content="data-processing,geoip,javascript,python,web-analytics">
<meta property="article:published_time" content="2015-02-11">
<meta property="article:modified_time" content="2015-02-11">
<link rel="stylesheet" type="text/css" href="/css/main.css">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
CommonHTML: {
scale: 93,
showMathMenu: false
},
tex2jax: {
"inlineMath": [["$","$"], ["\\(","\\)"]]
}
});
</script>
<script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>
</head>
<body class="entry-detail">
<header>
<div>
<img src="https://mmas.github.io/images/profile.jpg">
<a class="brand" href="/">Modesto Mas</a>
<span>Data/Python/DevOps Engineer</span>
<nav>
<ul>
<li><a href="/tags">Tags</a></li>
<li><a href="https://github.com/mmas/mmas.github.io/issues" target="_blank">Issues</a></li>
</ul>
</nav>
</div>
</header>
<section id="content" role="main">
<article>
<header>
<h1><a href="/web-visits-data-analytics-javascript-python--geoip">Getting web visits data for analytics with Javascript, Python and GeoIP</a></h1>
<time datetime="2015-02-11">Feb 11, 2015</time>
<a class="tag" href="/tags?tag=data-processing">data-processing</a>
<a class="tag" href="/tags?tag=geoip">geoip</a>
<a class="tag" href="/tags?tag=javascript">javascript</a>
<a class="tag" href="/tags?tag=python">python</a>
<a class="tag" href="/tags?tag=web-analytics">web-analytics</a>
</header>
<aside id="article-nav"></aside>
<section class="body">
<h2>Requirements</h2>
<pre>
% apt-get install -y geoip-database
% pip install python-dateutil pygeoip
</pre>
<h2>Browser data</h2>
<p>We are going to parse the navigator data to obtain the language, browser, operative system, screen resolution, density of pixels of the screen and a boolean to define if the user is using a touch device. This data will be POSTed to be analyzed and stored (in this example in the path <code>'/analytics'</code>).</p>
<p>The Javascript code:</p>
<pre>
var data, ua, platform, browser, os;
data = {
page: window.location.pathname.replace(/\/$/, ''),
language: navigator.language.slice(0, 2).toUpperCase(),
screen_resolution: window.screen.width + 'x' + window.screen.height,
screen_dpi: window.devicePixelRatio,
is_touch_device: 'ontouchstart' in window || 'onmsgesturechange' in window
};
ua = navigator.userAgent.toLowerCase();
platform = navigator.platform.toLowerCase();
browser = ua.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*([\d\.]+)/) || [];
if (/trident/.test(browser[1])) browser = 'ie';
else if (browser[2]) browser = browser[1];
else if (! browser.length) browser = 'other';
if (browser == 'msie') browser = 'ie';
data.browser = browser.toLowerCase();
if (ua.match(/android/)) os = 'android';
else if (ua.match(/(iphone|ipod|ipad)/)) os = 'ios';
else if (ua.match(/windows phone/)) os = 'windows-phone';
else if (ua.match(/blackberry/)) os = 'blackberry';
else if (platform.match(/mac/)) os = 'mac';
else if (platform.match(/win/)) os = 'windows';
else if (platform.match(/linux/)) os = 'linux';
else os = 'other';
data.os = os;
$.ajax({
url: '/analytics',
data: JSON.stringify(data),
type: 'POST'
});
</pre>
<h2>Server-side geo data</h2>
<p>I'm going to use <a href="http://www.tornadoweb.org/" target="_blank">Tornado</a> and <a href="http://cassandra.apache.org/" target="_blank">Cassandra</a>, the code is pretty straightforward so you can easily extrapolate it to your preferences (let's say Django and PostgreSQL, as an example).</p>
<p>You will need to download the <a href="http://dev.maxmind.com/geoip/geoip2/geolite2/" target="_blank">GeoLite City database</a> in your application data root (defined as <code>settings.DATA_ROOT</code>).</p>
<p>The Python code:</p>
<pre>
import os
import json
from tornado.web import RequestHandler
from pygeoip import GeoIP
import dateutil.parser
from app.models import Visit
from app import settings
class VisitController(RequestHandler):
def post(self):
self.set_status(204)
data = json.loads(self.request.body)
ip = self.request.remote_ip
if ip:
data['ip'] = ip
else:
return self.finish()
geo_db = GeoIP(os.path.join(settings.DATA_ROOT, 'GeoLiteCity.dat'))
try:
city = geo_db.record_by_addr(ip)
except:
return self.finish()
else:
data.update({'city': city['city'],
'country_code': city['country_code'],
'country_name': city['country_name'],
'continent': city['continent']})
data['date'] = dateutil.parser.parse(data['date'])
try:
Visit.create(**data)
except:
pass
return self.finish()
</pre>
</section>
</article>
</section>
<footer></footer>
<script type="text/javascript" src="/js/article.js"></script>
</body>
</html>