-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeoip2_service.py
57 lines (40 loc) · 1.2 KB
/
geoip2_service.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
import os
from functools import cached_property
from aiohttp import web
import geoip2.database
import geoip2.errors
def get_database_path():
return os.environ['CITY_DATABASE_PATH']
class GeoipLookup:
@cached_property
def reader(self):
return geoip2.database.Reader(get_database_path())
def lookup(self, ip):
return self.reader.city(ip)
geoip_lookup = GeoipLookup()
async def myip(request):
return web.json_response(dict(ip=request.remote))
async def lookup(request):
try:
resp = geoip_lookup.lookup(request.match_info['ip'])
except geoip2.errors.AddressNotFoundError:
return web.HTTPNotFound()
except:
return web.HTTPNotFound()
data = dict(
city=resp.city.name,
country=resp.country.name,
country_code=resp.country.iso_code,
location=dict(
latitude=resp.location.latitude,
longitude=resp.location.longitude,
),
postal_code=resp.postal.code,
)
return web.json_response(data)
web_app = web.Application()
web_app.add_routes([
web.get('/myip/', myip),
web.get('/lookup/{ip}/', lookup),
])
web_app.middlewares.append(web.normalize_path_middleware())