]>
git.ipfire.org Git - people/shoehn/ipfire.org.git/blob - webapp/backend/geoip.py
5 from databases
import Databases
6 from memcached
import Memcached
7 from misc
import Singleton
10 __metaclass__
= Singleton
14 return Databases().geoip
16 def _encode_ip(self
, addr
):
17 # We get a tuple if there were proxy headers.
18 addr
= addr
.split(", ")
22 # ip is calculated as described in http://dev.maxmind.com/geoip/csv
23 a1
, a2
, a3
, a4
= addr
.split(".")
33 return (16777216 * a1
) + (65536 * a2
) + (256 * a3
) + a4
35 def get_country(self
, addr
):
36 addr
= self
._encode
_ip
(addr
)
38 ret
= self
.db
.get("SELECT locations.country_code AS country_code FROM addresses \
39 JOIN locations ON locations.id = addresses.location \
40 WHERE %s BETWEEN start_ip_num AND end_ip_num LIMIT 1", addr
)
43 return ret
.country_code
45 def get_all(self
, addr
):
46 addr
= self
._encode
_ip
(addr
)
50 ret
= self
.db
.get("SELECT locations.* FROM addresses \
51 JOIN locations ON locations.id = addresses.location \
52 WHERE %s BETWEEN start_ip_num AND end_ip_num LIMIT 1", addr
)
57 # If location was not determinable
58 if ret
.latitude
== 0 and ret
.longitude
== 0:
63 def get_country_name(self
, code
):
67 "A1" : "Anonymous Proxy",
68 "A2" : "Satellite Provider",
70 "AP" : "Asia/Pacific Region",
73 # Return description of some exceptional codes.
79 ret
= self
.db
.get("SELECT name FROM iso3166_countries WHERE code = %s LIMIT 1", code
)
83 # Fix some weird strings
84 name
= re
.sub(r
"(.*) (.* Republic of)", r
"\2 \1", name
)
89 if __name__
== "__main__":
92 print g
.get_country("123.123.123.123")
93 print g
.get_all("123.123.123.123")