mirror of
https://github.com/django/django.git
synced 2025-07-04 09:49:12 +00:00
gis: Fixed #6196 in GeoIP refactor. Added unit tests, improved path setup, and made mostly compatible w/existing MaxMind Python API.
git-svn-id: http://code.djangoproject.com/svn/django/branches/gis@6918 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
40a7292a8d
commit
9270d47d80
@ -3,9 +3,12 @@ from copy import copy
|
||||
from unittest import TestSuite, TextTestRunner
|
||||
from django.contrib.gis.gdal import HAS_GDAL
|
||||
try:
|
||||
from django.contrib.gis.tests.utils import mysql, oracle
|
||||
from django.contrib.gis.tests.utils import mysql, oracle, postgis
|
||||
except:
|
||||
mysql, oracle = (False, False)
|
||||
mysql, oracle, postgis = (False, False, False)
|
||||
from django.contrib.gis.utils import HAS_GEOIP
|
||||
from django.conf import settings
|
||||
if not settings._target: settings.configure()
|
||||
|
||||
# Tests that require use of a spatial database (e.g., creation of models)
|
||||
test_models = ['geoapp']
|
||||
@ -20,8 +23,9 @@ if HAS_GDAL:
|
||||
# TODO: There is a problem with the `syncdb` SQL for the LayerMapping
|
||||
# tests on Oracle.
|
||||
test_models += ['distapp']
|
||||
else:
|
||||
elif postgis:
|
||||
test_models += ['distapp', 'layermap']
|
||||
|
||||
test_suite_names += [
|
||||
'test_gdal_driver',
|
||||
'test_gdal_ds',
|
||||
@ -33,6 +37,10 @@ if HAS_GDAL:
|
||||
else:
|
||||
print >>sys.stderr, "GDAL not available - no GDAL tests will be run."
|
||||
|
||||
if HAS_GEOIP:
|
||||
if hasattr(settings, 'GEOIP_PATH'):
|
||||
test_suite_names.append('test_geoip')
|
||||
|
||||
def suite():
|
||||
"Builds a test suite for the GIS package."
|
||||
s = TestSuite()
|
||||
@ -77,7 +85,6 @@ def run_tests(module_list, verbosity=1, interactive=True):
|
||||
|
||||
Finally, the tests may be run by invoking `./manage.py test`.
|
||||
"""
|
||||
from django.conf import settings
|
||||
from django.contrib.gis.db.backend import create_spatial_db
|
||||
from django.db import connection
|
||||
from django.test.utils import destroy_test_db
|
||||
@ -86,10 +93,13 @@ def run_tests(module_list, verbosity=1, interactive=True):
|
||||
old_debug = settings.DEBUG
|
||||
old_name = copy(settings.DATABASE_NAME)
|
||||
old_installed = copy(settings.INSTALLED_APPS)
|
||||
new_installed = copy(settings.INSTALLED_APPS)
|
||||
|
||||
# Want DEBUG to be set to False.
|
||||
settings.DEBUG = False
|
||||
|
||||
from django.db.models import loading
|
||||
|
||||
# Creating the test suite, adding the test models to INSTALLED_APPS, and
|
||||
# adding the model test suites to our suite package.
|
||||
test_suite = suite()
|
||||
@ -99,16 +109,18 @@ def run_tests(module_list, verbosity=1, interactive=True):
|
||||
test_module_name = 'tests_mysql'
|
||||
else:
|
||||
test_module_name = 'tests'
|
||||
settings.INSTALLED_APPS.append(module_name)
|
||||
new_installed.append(module_name)
|
||||
|
||||
# Getting the test suite
|
||||
tsuite = getattr(__import__('django.contrib.gis.tests.%s' % test_model, globals(), locals(), [test_module_name]), test_module_name)
|
||||
test_suite.addTest(tsuite.suite())
|
||||
|
||||
|
||||
# Resetting the loaded flag to take into account what we appended to
|
||||
# the INSTALLED_APPS (since this routine is invoked through
|
||||
# django/core/management, it caches the apps; this ensures that syncdb
|
||||
# will see our appended models)
|
||||
from django.db.models import loading
|
||||
loading._loaded = False
|
||||
settings.INSTALLED_APPS = new_installed
|
||||
loading.cache.loaded = False
|
||||
|
||||
# Creating the test spatial database.
|
||||
create_spatial_db(test=True, verbosity=verbosity)
|
||||
|
104
django/contrib/gis/tests/test_geoip.py
Normal file
104
django/contrib/gis/tests/test_geoip.py
Normal file
@ -0,0 +1,104 @@
|
||||
import os, unittest
|
||||
from django.db import settings
|
||||
from django.contrib.gis.geos import GEOSGeometry
|
||||
from django.contrib.gis.utils import GeoIP, GeoIPException
|
||||
|
||||
# Note: Requires use of both the GeoIP country and city datasets.
|
||||
# The GEOIP_DATA path should be the only setting set (the directory
|
||||
# should contain links or the actual database files 'GeoIP.dat' and
|
||||
# 'GeoLiteCity.dat'.
|
||||
class GeoIPTest(unittest.TestCase):
|
||||
|
||||
def test01_init(self):
|
||||
"Testing GeoIP initialization."
|
||||
g1 = GeoIP() # Everything inferred from GeoIP path
|
||||
path = settings.GEOIP_PATH
|
||||
g2 = GeoIP(path, 0) # Passing in data path explicitly.
|
||||
g3 = GeoIP.open(path, 0) # MaxMind Python API syntax.
|
||||
|
||||
for g in (g1, g2, g3):
|
||||
self.assertEqual(True, bool(g._country))
|
||||
self.assertEqual(True, bool(g._city))
|
||||
|
||||
# Only passing in the location of one database.
|
||||
city = os.path.join(path, 'GeoLiteCity.dat')
|
||||
cntry = os.path.join(path, 'GeoIP.dat')
|
||||
g4 = GeoIP(city, country='')
|
||||
self.assertEqual(None, g4._country)
|
||||
g5 = GeoIP(cntry, city='')
|
||||
self.assertEqual(None, g5._city)
|
||||
|
||||
# Improper parameters.
|
||||
bad_params = (23, 'foo', 15.23)
|
||||
for bad in bad_params:
|
||||
self.assertRaises(GeoIPException, GeoIP, cache=bad)
|
||||
if isinstance(bad, basestring):
|
||||
e = GeoIPException
|
||||
else:
|
||||
e = TypeError
|
||||
self.assertRaises(e, GeoIP, bad, 0)
|
||||
|
||||
def test02_bad_query(self):
|
||||
"Testing GeoIP query parameter checking."
|
||||
cntry_g = GeoIP(city='<foo>')
|
||||
# No city database available, these calls should fail.
|
||||
self.assertRaises(GeoIPException, cntry_g.city, 'google.com')
|
||||
self.assertRaises(GeoIPException, cntry_g.coords, 'yahoo.com')
|
||||
|
||||
# Non-string query should raise TypeError
|
||||
self.assertRaises(TypeError, cntry_g.country_code, 17)
|
||||
self.assertRaises(TypeError, cntry_g.country_name, GeoIP)
|
||||
|
||||
def test03_country(self):
|
||||
"Testing GeoIP country querying methods."
|
||||
g = GeoIP(city='<foo>')
|
||||
|
||||
fqdn = 'www.google.com'
|
||||
addr = '12.215.42.19'
|
||||
|
||||
for query in (fqdn, addr):
|
||||
for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name):
|
||||
self.assertEqual('US', func(query))
|
||||
for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name):
|
||||
self.assertEqual('United States', func(query))
|
||||
self.assertEqual({'country_code' : 'US', 'country_name' : 'United States'},
|
||||
g.country(query))
|
||||
|
||||
def test04_city(self):
|
||||
"Testing GeoIP city querying methods."
|
||||
g = GeoIP(country='<foo>')
|
||||
|
||||
addr = '130.80.29.3'
|
||||
fqdn = 'chron.com'
|
||||
for query in (fqdn, addr):
|
||||
# Country queries should still work.
|
||||
for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name):
|
||||
self.assertEqual('US', func(query))
|
||||
for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name):
|
||||
self.assertEqual('United States', func(query))
|
||||
self.assertEqual({'country_code' : 'US', 'country_name' : 'United States'},
|
||||
g.country(query))
|
||||
|
||||
# City information dictionary.
|
||||
d = g.city(query)
|
||||
self.assertEqual('USA', d['country_code3'])
|
||||
self.assertEqual('Houston', d['city'])
|
||||
self.assertEqual('TX', d['region'])
|
||||
self.assertEqual('77002', d['postal_code'])
|
||||
self.assertEqual(713, d['area_code'])
|
||||
geom = g.geos(query)
|
||||
self.failIf(not isinstance(geom, GEOSGeometry))
|
||||
lon, lat = (-95.366996765, 29.752300262)
|
||||
lat_lon = g.lat_lon(query)
|
||||
lat_lon = (lat_lon[1], lat_lon[0])
|
||||
for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon):
|
||||
self.assertAlmostEqual(lon, tup[0], 9)
|
||||
self.assertAlmostEqual(lat, tup[1], 9)
|
||||
|
||||
def suite():
|
||||
s = unittest.TestSuite()
|
||||
s.addTest(unittest.makeSuite(GeoIPTest))
|
||||
return s
|
||||
|
||||
def run(verbosity=2):
|
||||
unittest.TextTestRunner(verbosity=verbosity).run(suite())
|
@ -15,7 +15,7 @@ if HAS_GDAL:
|
||||
|
||||
# Attempting to import the GeoIP class.
|
||||
try:
|
||||
from django.contrib.gis.utils.geoip import GeoIP
|
||||
from django.contrib.gis.utils.geoip import GeoIP, GeoIPException
|
||||
HAS_GEOIP = True
|
||||
except:
|
||||
HAS_GEOIP = False
|
||||
|
@ -1,15 +1,16 @@
|
||||
"""
|
||||
This module houses the GeoIP object, a ctypes wrapper for the MaxMind GeoIP(R)
|
||||
C API (http://www.maxmind.com/app/c).
|
||||
C API (http://www.maxmind.com/app/c). This is an alternative to the GPL
|
||||
licensed Python GeoIP interface provided by MaxMind.
|
||||
|
||||
GeoIP(R) is a registered trademark of MaxMind, LLC of Boston, Massachusetts.
|
||||
|
||||
For IP-based geolocation, this module requires the GeoLite Country and City
|
||||
datasets, in binary format (CSV will not work!). The datasets may be
|
||||
downloaded from MaxMind at http://www.maxmind.com/download/geoip/database/.
|
||||
Grab GeoIP.dat.gz and GeoLiteCity.dat.gz, and unzip them in the directory
|
||||
corresponding to settings.GEOIP_PATH. See the GeoIP docstring and examples
|
||||
below for more details.
|
||||
datasets, in binary format (CSV will not work!). The datasets may be
|
||||
downloaded from MaxMind at http://www.maxmind.com/download/geoip/database/.
|
||||
Grab GeoIP.dat.gz and GeoLiteCity.dat.gz, and unzip them in the directory
|
||||
corresponding to settings.GEOIP_PATH. See the GeoIP docstring and examples
|
||||
below for more details.
|
||||
|
||||
TODO: Verify compatibility with Windows.
|
||||
|
||||
@ -38,52 +39,42 @@
|
||||
'POINT (-95.2087020874023438 39.0392990112304688)'
|
||||
"""
|
||||
import os, re
|
||||
from ctypes import c_char_p, c_float, c_int, string_at, Structure, CDLL, POINTER
|
||||
from ctypes import c_char_p, c_float, c_int, Structure, CDLL, POINTER
|
||||
from django.conf import settings
|
||||
if not settings._target: settings.configure()
|
||||
|
||||
# The Exception class for GeoIP Errors.
|
||||
# Creating the settings dictionary with any settings, if needed.
|
||||
GEOIP_SETTINGS = dict((key, getattr(settings, key))
|
||||
for key in ('GEOIP_PATH', 'GEOIP_LIBRARY_PATH', 'GEOIP_COUNTRY', 'GEOIP_CITY')
|
||||
if hasattr(settings, key))
|
||||
lib_name = GEOIP_SETTINGS.get('GEOIP_LIBRARY_PATH', None)
|
||||
|
||||
# GeoIP Exception class.
|
||||
class GeoIPException(Exception): pass
|
||||
|
||||
# The shared library for the GeoIP C API. May be downloaded
|
||||
# from http://www.maxmind.com/download/geoip/api/c/
|
||||
if os.name == 'nt':
|
||||
ext = '.dll'
|
||||
if lib_name:
|
||||
pass
|
||||
elif os.name == 'nt':
|
||||
lib_name = 'libGeoIP.dll'
|
||||
elif os.name == 'posix':
|
||||
platform = os.uname()[0]
|
||||
if platform in ('Linux', 'SunOS'):
|
||||
ext = '.so'
|
||||
elif platofm == 'Darwin':
|
||||
ext = '.dylib'
|
||||
if platform == 'Darwin':
|
||||
lib_name = 'libGeoIP.dylib'
|
||||
else:
|
||||
raise GeoIPException('Unknown POSIX platform "%s"' % platform)
|
||||
lgeoip = CDLL('libGeoIP' + ext)
|
||||
lib_name = 'libGeoIP.so'
|
||||
else:
|
||||
raise GeoIPException('Unknown POSIX platform "%s"' % platform)
|
||||
lgeoip = CDLL(lib_name)
|
||||
|
||||
# A regular expression for recognizing IP addresses
|
||||
# Regular expressions for recognizing IP addresses and the GeoIP
|
||||
# free database editions.
|
||||
ipregex = re.compile(r'^(?P<w>\d\d?\d?)\.(?P<x>\d\d?\d?)\.(?P<y>\d\d?\d?)\.(?P<z>\d\d?\d?)$')
|
||||
free_regex = re.compile(r'^GEO-\d{3}FREE')
|
||||
lite_regex = re.compile(r'^GEO-\d{3}LITE')
|
||||
|
||||
# The flags for GeoIP memory caching.
|
||||
# GEOIP_STANDARD - read database from filesystem, uses least memory.
|
||||
#
|
||||
# GEOIP_MEMORY_CACHE - load database into memory, faster performance
|
||||
# but uses more memory
|
||||
#
|
||||
# GEOIP_CHECK_CACHE - check for updated database. If database has been updated,
|
||||
# reload filehandle and/or memory cache.
|
||||
#
|
||||
# GEOIP_INDEX_CACHE - just cache
|
||||
# the most frequently accessed index portion of the database, resulting
|
||||
# in faster lookups than GEOIP_STANDARD, but less memory usage than
|
||||
# GEOIP_MEMORY_CACHE - useful for larger databases such as
|
||||
# GeoIP Organization and GeoIP City. Note, for GeoIP Country, Region
|
||||
# and Netspeed databases, GEOIP_INDEX_CACHE is equivalent to GEOIP_MEMORY_CACHE
|
||||
#
|
||||
cache_options = {0 : c_int(0), # GEOIP_STANDARD
|
||||
1 : c_int(1), # GEOIP_MEMORY_CACHE
|
||||
2 : c_int(2), # GEOIP_CHECK_CACHE
|
||||
4 : c_int(4), # GEOIP_INDEX_CACHE
|
||||
}
|
||||
|
||||
# GeoIPRecord C Structure definition.
|
||||
#### GeoIP C Structure definitions ####
|
||||
class GeoIPRecord(Structure):
|
||||
_fields_ = [('country_code', c_char_p),
|
||||
('country_code3', c_char_p),
|
||||
@ -96,155 +87,210 @@ class GeoIPRecord(Structure):
|
||||
('dma_code', c_int),
|
||||
('area_code', c_int),
|
||||
]
|
||||
class GeoIPTag(Structure): pass
|
||||
|
||||
# ctypes function prototypes
|
||||
record_by_addr = lgeoip.GeoIP_record_by_addr
|
||||
record_by_addr.restype = POINTER(GeoIPRecord)
|
||||
record_by_name = lgeoip.GeoIP_record_by_name
|
||||
record_by_name.restype = POINTER(GeoIPRecord)
|
||||
#### ctypes function prototypes ####
|
||||
RECTYPE = POINTER(GeoIPRecord)
|
||||
DBTYPE = POINTER(GeoIPTag)
|
||||
|
||||
# The exception class for GeoIP Errors.
|
||||
class GeoIPException(Exception): pass
|
||||
# For retrieving records by name or address.
|
||||
def record_output(func):
|
||||
func.restype = RECTYPE
|
||||
return func
|
||||
rec_by_addr = record_output(lgeoip.GeoIP_record_by_addr)
|
||||
rec_by_name = record_output(lgeoip.GeoIP_record_by_name)
|
||||
|
||||
# For opening up GeoIP databases.
|
||||
geoip_open = lgeoip.GeoIP_open
|
||||
geoip_open.restype = DBTYPE
|
||||
|
||||
# String output routines.
|
||||
def string_output(func):
|
||||
func.restype = c_char_p
|
||||
return func
|
||||
geoip_dbinfo = string_output(lgeoip.GeoIP_database_info)
|
||||
cntry_code_by_addr = string_output(lgeoip.GeoIP_country_code_by_addr)
|
||||
cntry_code_by_name = string_output(lgeoip.GeoIP_country_code_by_name)
|
||||
cntry_name_by_addr = string_output(lgeoip.GeoIP_country_name_by_addr)
|
||||
cntry_name_by_name = string_output(lgeoip.GeoIP_country_name_by_name)
|
||||
|
||||
#### GeoIP class ####
|
||||
class GeoIP(object):
|
||||
def __init__(self, path=None, country=None, city=None,
|
||||
cache=0):
|
||||
# The flags for GeoIP memory caching.
|
||||
# GEOIP_STANDARD - read database from filesystem, uses least memory.
|
||||
#
|
||||
# GEOIP_MEMORY_CACHE - load database into memory, faster performance
|
||||
# but uses more memory
|
||||
#
|
||||
# GEOIP_CHECK_CACHE - check for updated database. If database has been updated,
|
||||
# reload filehandle and/or memory cache.
|
||||
#
|
||||
# GEOIP_INDEX_CACHE - just cache
|
||||
# the most frequently accessed index portion of the database, resulting
|
||||
# in faster lookups than GEOIP_STANDARD, but less memory usage than
|
||||
# GEOIP_MEMORY_CACHE - useful for larger databases such as
|
||||
# GeoIP Organization and GeoIP City. Note, for GeoIP Country, Region
|
||||
# and Netspeed databases, GEOIP_INDEX_CACHE is equivalent to GEOIP_MEMORY_CACHE
|
||||
#
|
||||
GEOIP_STANDARD = 0
|
||||
GEOIP_MEMORY_CACHE = 1
|
||||
GEOIP_CHECK_CACHE = 2
|
||||
GEOIP_INDEX_CACHE = 4
|
||||
cache_options = dict((opt, None) for opt in (0, 1, 2, 4))
|
||||
|
||||
def __init__(self, path=None, cache=0, country=None, city=None):
|
||||
"""
|
||||
Initializes the GeoIP object, no parameters are required to use default
|
||||
settings. Keyword arguments may be passed in to customize the locations
|
||||
of the GeoIP data sets.
|
||||
settings. Keyword arguments may be passed in to customize the locations
|
||||
of the GeoIP data sets.
|
||||
|
||||
* path: Base directory where the GeoIP data files (*.dat) are located.
|
||||
* path: Base directory to where GeoIP data is located or the full path
|
||||
to where the city or country data files (*.dat) are located.
|
||||
Assumes that both the city and country data sets are located in
|
||||
this directory. Overrides the GEOIP_PATH settings attribute.
|
||||
this directory; overrides the GEOIP_PATH settings attribute.
|
||||
|
||||
* cache: The cache settings when opening up the GeoIP datasets,
|
||||
and may be an integer in (0, 1, 2, 4) corresponding to
|
||||
the GEOIP_STANDARD, GEOIP_MEMORY_CACHE, GEOIP_CHECK_CACHE,
|
||||
and GEOIP_INDEX_CACHE `GeoIPOptions` C API settings,
|
||||
respectively. Defaults to 0, meaning that the data is read
|
||||
from the disk.
|
||||
|
||||
* country: The name of the GeoIP country data file. Defaults to
|
||||
'GeoIP.dat'; overrides the GEOIP_COUNTRY settings attribute.
|
||||
|
||||
* city: The name of the GeoIP city data file. Defaults to
|
||||
'GeoLiteCity.dat'; overrides the GEOIP_CITY settings attribute.
|
||||
|
||||
* cache: The cache settings when opening up the GeoIP datasets,
|
||||
and may be an integer in (0, 1, 2, 4). Defaults to 0, meaning
|
||||
that the data is read from the disk.
|
||||
"""
|
||||
|
||||
# Checking the given cache option.
|
||||
if cache in cache_options:
|
||||
self._cache = cache_options[cache]
|
||||
if cache in self.cache_options:
|
||||
self._cache = self.cache_options[cache]
|
||||
else:
|
||||
raise GeoIPException('Invalid caching option: %s' % cache)
|
||||
|
||||
# Getting the GeoIP data path.
|
||||
if not path:
|
||||
try:
|
||||
self._path = settings.GEOIP_PATH
|
||||
except AttributeError:
|
||||
raise GeoIPException('Must specify GEOIP_PATH in your settings.py')
|
||||
else:
|
||||
self._path = path
|
||||
if not os.path.isdir(self._path):
|
||||
raise GeoIPException('GEOIP_PATH must be set to a directory.')
|
||||
path = GEOIP_SETTINGS.get('GEOIP_PATH', None)
|
||||
if not path: raise GeoIPException('GeoIP path must be provided via parameter or the GEOIP_PATH setting.')
|
||||
if not isinstance(path, basestring):
|
||||
raise TypeError('Invalid path type: %s' % type(path).__name__)
|
||||
|
||||
# Getting the GeoIP country data file.
|
||||
if not country:
|
||||
try:
|
||||
cntry_file = settings.GEOIP_COUNTRY
|
||||
except AttributeError:
|
||||
cntry_file = 'GeoIP.dat'
|
||||
cntry_ptr, city_ptr = (None, None)
|
||||
if os.path.isdir(path):
|
||||
# Getting the country and city files using the settings
|
||||
# dictionary. If no settings are provided, default names
|
||||
# are assigned.
|
||||
country = os.path.join(path, country or GEOIP_SETTINGS.get('GEOIP_COUNTRY', 'GeoIP.dat'))
|
||||
city = os.path.join(path, city or GEOIP_SETTINGS.get('GEOIP_CITY', 'GeoLiteCity.dat'))
|
||||
elif os.path.isfile(path):
|
||||
# Otherwise, some detective work will be needed to figure
|
||||
# out whether the given database path is for the GeoIP country
|
||||
# or city databases.
|
||||
ptr = geoip_open(path, cache)
|
||||
info = geoip_dbinfo(ptr)
|
||||
if lite_regex.match(info):
|
||||
# GeoLite City database.
|
||||
city, city_ptr = path, ptr
|
||||
elif free_regex.match(info):
|
||||
# GeoIP Country database.
|
||||
country, cntry_ptr = path, ptr
|
||||
else:
|
||||
raise GeoIPException('Unable to recognize database edition: %s' % info)
|
||||
else:
|
||||
cntry_file = country
|
||||
self._country_file = os.path.join(self._path, cntry_file)
|
||||
raise GeoIPException('GeoIP path must be a valid file or directory.')
|
||||
|
||||
# `_init_db` does the dirty work.
|
||||
self._init_db(country, cache, '_country', cntry_ptr)
|
||||
self._init_db(city, cache, '_city', city_ptr)
|
||||
|
||||
# Getting the GeoIP city data file.
|
||||
if not city:
|
||||
try:
|
||||
city_file = settings.GEOIP_CITY
|
||||
except AttributeError:
|
||||
city_file = 'GeoLiteCity.dat'
|
||||
else:
|
||||
city_file = city
|
||||
self._city_file = os.path.join(self._path, city_file)
|
||||
def _init_db(self, db_file, cache, attname, ptr=None):
|
||||
"Helper routine for setting GeoIP ctypes database properties."
|
||||
if ptr:
|
||||
# Pointer already retrieved.
|
||||
pass
|
||||
elif os.path.isfile(db_file or ''):
|
||||
ptr = geoip_open(db_file, cache)
|
||||
setattr(self, attname, ptr)
|
||||
setattr(self, '%s_file' % attname, db_file)
|
||||
|
||||
# Opening up the GeoIP country data file.
|
||||
if os.path.isfile(self._country_file):
|
||||
self._country = lgeoip.GeoIP_open(c_char_p(self._country_file), self._cache)
|
||||
else:
|
||||
self._country = None
|
||||
def _check_query(self, query, country=False, city=False, city_or_country=False):
|
||||
"Helper routine for checking the query and database availability."
|
||||
# Making sure a string was passed in for the query.
|
||||
if not isinstance(query, basestring):
|
||||
raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__)
|
||||
|
||||
# Opening the GeoIP city data file.
|
||||
if os.path.isfile(self._city_file):
|
||||
self._city = lgeoip.GeoIP_open(c_char_p(self._city_file), self._cache)
|
||||
else:
|
||||
self._city = None
|
||||
|
||||
def country(self, query):
|
||||
"""
|
||||
Returns a dictonary with with the country code and name when given an
|
||||
IP address or a Fully Qualified Domain Name (FQDN). For example, both
|
||||
'24.124.1.80' and 'djangoproject.com' are valid parameters.
|
||||
"""
|
||||
if self._country is None:
|
||||
# Extra checks for the existence of country and city databases.
|
||||
if city_or_country and self._country is None and self._city is None:
|
||||
raise GeoIPException('Invalid GeoIP country and city data files.')
|
||||
elif country and self._country is None:
|
||||
raise GeoIPException('Invalid GeoIP country data file: %s' % self._country_file)
|
||||
|
||||
if ipregex.match(query):
|
||||
# If an IP address was passed in.
|
||||
code = lgeoip.GeoIP_country_code_by_addr(self._country, c_char_p(query))
|
||||
name = lgeoip.GeoIP_country_name_by_addr(self._country, c_char_p(query))
|
||||
else:
|
||||
# If a FQDN was passed in.
|
||||
code = lgeoip.GeoIP_country_code_by_name(self._country, c_char_p(query))
|
||||
name = lgeoip.GeoIP_country_name_by_name(self._country, c_char_p(query))
|
||||
|
||||
# Checking our returned country code and name, setting each to
|
||||
# None, if pointer is invalid.
|
||||
if bool(code): code = string_at(code)
|
||||
else: code = None
|
||||
if bool(name): name = string_at(name)
|
||||
else: name = None
|
||||
|
||||
# Returning the country code and name
|
||||
return {'country_code' : code,
|
||||
'country_name' : name,
|
||||
}
|
||||
elif city and self._city is None:
|
||||
raise GeoIPException('Invalid GeoIP city data file: %s' % self._city_file)
|
||||
|
||||
def city(self, query):
|
||||
"""
|
||||
Returns a dictionary of city information for the given IP address or
|
||||
Fully Qualified Domain Name (FQDN). Some information in the dictionary
|
||||
may be undefined (None).
|
||||
Returns a dictionary of city information for the given IP address or
|
||||
Fully Qualified Domain Name (FQDN). Some information in the dictionary
|
||||
may be undefined (None).
|
||||
"""
|
||||
if self._city is None:
|
||||
raise GeoIPException('Invalid GeoIP country data file: %s' % self._city_file)
|
||||
|
||||
self._check_query(query, city=True)
|
||||
if ipregex.match(query):
|
||||
# If an IP address was passed in
|
||||
ptr = record_by_addr(self._city, c_char_p(query))
|
||||
ptr = rec_by_addr(self._city, c_char_p(query))
|
||||
else:
|
||||
# If a FQDN was passed in.
|
||||
ptr = record_by_name(self._city, c_char_p(query))
|
||||
ptr = rec_by_name(self._city, c_char_p(query))
|
||||
|
||||
# Checking the pointer to the C structure, if valid pull out elements
|
||||
# into a dicionary and return.
|
||||
# into a dicionary and return.
|
||||
if bool(ptr):
|
||||
record = ptr.contents
|
||||
return dict((tup[0], getattr(record, tup[0])) for tup in record._fields_)
|
||||
else:
|
||||
return None
|
||||
|
||||
def country_code(self, query):
|
||||
"Returns the country code for the given IP Address or FQDN."
|
||||
self._check_query(query, city_or_country=True)
|
||||
if self._country:
|
||||
if ipregex.match(query): return cntry_code_by_addr(self._country, query)
|
||||
else: return cntry_code_by_name(self._country, query)
|
||||
else:
|
||||
return self.city(query)['country_code']
|
||||
|
||||
def country_name(self, query):
|
||||
"Returns the country name for the given IP Address or FQDN."
|
||||
self._check_query(query, city_or_country=True)
|
||||
if self._country:
|
||||
if ipregex.match(query): return cntry_name_by_addr(self._country, query)
|
||||
else: return cntry_name_by_name(self._country, query)
|
||||
else:
|
||||
return self.city(query)['country_name']
|
||||
|
||||
def country(self, query):
|
||||
"""
|
||||
Returns a dictonary with with the country code and name when given an
|
||||
IP address or a Fully Qualified Domain Name (FQDN). For example, both
|
||||
'24.124.1.80' and 'djangoproject.com' are valid parameters.
|
||||
"""
|
||||
# Returning the country code and name
|
||||
return {'country_code' : self.country_code(query),
|
||||
'country_name' : self.country_name(query),
|
||||
}
|
||||
|
||||
#### Coordinate retrieval routines ####
|
||||
def _coords(self, query, ordering):
|
||||
def coords(self, query, ordering=('longitude', 'latitude')):
|
||||
cdict = self.city(query)
|
||||
if cdict is None: return None
|
||||
else: return tuple(cdict[o] for o in ordering)
|
||||
|
||||
|
||||
def lon_lat(self, query):
|
||||
"Returns a tuple of the (longitude, latitude) for the given query."
|
||||
return self._coords(query, ('longitude', 'latitude'))
|
||||
return self.coords(query)
|
||||
|
||||
def lat_lon(self, query):
|
||||
"Returns a tuple of the (latitude, longitude) for the given query."
|
||||
return self._coords(query, ('latitude', 'longitude'))
|
||||
return self.coords(query, ('latitude', 'longitude'))
|
||||
|
||||
def geos(self, query):
|
||||
"Returns a GEOS Point object for the given query."
|
||||
@ -261,7 +307,7 @@ class GeoIP(object):
|
||||
if self._country is None:
|
||||
ci = 'No GeoIP Country data in "%s"' % self._country_file
|
||||
else:
|
||||
ci = string_at(lgeoip.GeoIP_database_info(self._country))
|
||||
ci = geoip_dbinfo(self._country)
|
||||
return ci
|
||||
country_info = property(country_info)
|
||||
|
||||
@ -270,7 +316,7 @@ class GeoIP(object):
|
||||
if self._city is None:
|
||||
ci = 'No GeoIP City data in "%s"' % self._city_file
|
||||
else:
|
||||
ci = string_at(lgeoip.GeoIP_database_info(self._city))
|
||||
ci = geoip_dbinfo(self._city)
|
||||
return ci
|
||||
city_info = property(city_info)
|
||||
|
||||
@ -278,3 +324,22 @@ class GeoIP(object):
|
||||
"Returns information about all GeoIP databases in use."
|
||||
return 'Country:\n\t%s\nCity:\n\t%s' % (self.country_info, self.city_info)
|
||||
info = property(info)
|
||||
|
||||
#### Methods for compatibility w/the GeoIP-Python API. ####
|
||||
@classmethod
|
||||
def open(cls, full_path, cache):
|
||||
return GeoIP(full_path, cache)
|
||||
|
||||
def _rec_by_arg(self, arg):
|
||||
if self._city:
|
||||
return self.city(arg)
|
||||
else:
|
||||
return self.country(arg)
|
||||
region_by_addr = city
|
||||
region_by_name = city
|
||||
record_by_addr = _rec_by_arg
|
||||
record_by_name = _rec_by_arg
|
||||
country_code_by_addr = country_code
|
||||
country_code_by_name = country_code
|
||||
country_name_by_addr = country_name
|
||||
country_name_by_name = country_name
|
||||
|
Loading…
x
Reference in New Issue
Block a user