Apr 28

Improved GeoIP Lookup Function in Python

An improved python function for calling a better Geo IP lookup service

The other day I found another GeoIP lookup service that happens to also return JSON, which is awesome given the great JSON support in Python. The JSON returned looks like this:

"Ip" : "",
"Status" : "OK",
"CountryCode" : "US",
"CountryName" : "United States",
"RegionCode" : "06",
"RegionName" : "California",
"City" : "Mountain View",
"ZipPostalCode" : "94043",
"Latitude" : "37.4192",
"Longitude" : "-122.057",

Today, the service I was using seems to be dead so I quickly reimplemented my function and it turned out much cleaner.

from urllib import urlopen, quote
import simplejson

GEOIP_LOOKUP_URL = 'http://ipinfodb.com/ip_query.php?ip=%s&output=json'

def geo_ip_lookup(ip_address):
    Look up the geo information based on the IP address passed in
    lookup_url = GEOIP_LOOKUP_URL % ip_address
    json_response = simplejson.loads(urlopen(lookup_url).read())

    return {
            'country_code': json_response['CountryCode'],
            'country_name': json_response['CountryName'],
            'locality': json_response['City'],
            'region': json_response['RegionName'],
            'longitude': json_response['Longitude'],
            'latitude': json_response['Latitude']

Just like before, from the interpreter:

>>> geo_ip_lookup('')
{'locality': u'Gent', 'region': u'Oost-Vlaanderen', 'longitude': u'3.7167', 'latitude': u'51.05', 'country_code': u'BE', 'country_name': u'Belgium'}



Powered by my hackings on Django-Mingus a Django project, PostgreSQL, memcached, nginx, Apache + mod_wsgi, Ubuntu, Rackspace Cloud,...

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

html5 | top