]>
git.ipfire.org Git - people/shoehn/ipfire.org.git/blob - www/webapp/backend/geoip.py
5 from databases
import Databases
6 from misc
import Singleton
9 __metaclass__
= Singleton
12 self
.__country
_codes
= self
.db
.query("SELECT code, name FROM iso3166_countries")
16 return Databases().geoip
18 def __encode_ip(self
, addr
):
19 # We get a tuple if there were proxy headers.
20 addr
= addr
.split(", ")
24 # ip is calculated as described in http://ipinfodb.com/ip_database.php
25 a1
, a2
, a3
, a4
= addr
.split(".")
27 return int(((int(a1
) * 256 + int(a2
)) * 256 + int(a3
)) * 256 + int(a4
) + 100)
29 def get_country(self
, addr
):
30 return self
.db
.get("SELECT * FROM ip_group_country WHERE ip_start <= %s \
31 ORDER BY ip_start DESC LIMIT 1;", self
.__encode
_ip
(addr
)).country_code
.lower()
33 def get_all(self
, addr
):
34 # XXX should be done with a join
35 location
= self
.db
.get("SELECT location FROM ip_group_city WHERE ip_start <= %s \
36 ORDER BY ip_start DESC LIMIT 1;", self
.__encode
_ip
(addr
)).location
38 return self
.db
.get("SELECT * FROM locations WHERE id = %s", int(location
))
40 def get_country_name(self
, code
):
44 for country
in self
.__country
_codes
:
45 if country
.code
== code
:
49 # Fix some weird strings
50 name
= re
.sub(r
"(.*) (.* Republic of)", r
"\2 \1", name
)
55 if __name__
== "__main__":
58 print g
.get_country("123.123.123.123")
59 print g
.get_all("123.123.123.123")