This repository was archived by the owner on May 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeoloc.py
More file actions
76 lines (63 loc) · 1.77 KB
/
geoloc.py
File metadata and controls
76 lines (63 loc) · 1.77 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
#
# Geolocation using the hostip.info API
#
import json
import urllib2
class Geoloc:
_cachefmt = "/var/tmp/geoloc-{0}.json"
_cache_located = False
_url_located = False
def __init__(self, ip=None):
self._ip = ip
self._lng = float('NaN')
self._lat = float('NaN')
self._readcache()
self.update()
def _sync(self):
try:
data = json.loads(self._data)
self._lng = float(data['lng'])
self._lat = float(data['lat'])
except:
""
def _readcache(self):
cachename = self._cachefmt.format(self._ip if self._ip else "default")
try:
cf = open(cachename, 'r')
self._data = cf.read()
cf.close()
self._sync()
self._cache_located = True
except:
""
def _writecache(self):
cachename = self._cachefmt.format(self._ip if self._ip else "default")
try:
cf = open(cachename, 'w')
cf.write(self._data)
cf.close()
except:
""
def update(self):
try:
url = 'http://api.hostip.info/get_json.php?position=true?ip='.\
format(self._ip if self._ip else '')
data = urllib2.urlopen(url=url, timeout=2)
self._data = data.read()
self._sync()
self._writecache()
self._url_located = True
except:
""
def located(self):
return self.lng != float('NaN') and self.lat != float('NaN')
@property
def lat(self):
if not self._url_located:
self.update()
return self._lat
@property
def lng(self):
if not self._url_located:
self.update()
return self._lng