Mar 10

Quick and Dirty GeoIP Lookup Function in Python

A python function for calling Geo IP lookup service

I found a free GeoIP lookup service, that happens to have a simple API for getting the result in XML: The returned XML looks like this:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<HostipLookupResultSet version="1.0.0" xmlns="" xmlns:gml="" xmlns:xsi="" xsi:schemaLocation="">
 <gml:description<This is the Hostip Lookup Service</gml:description>

   <gml:name>Miami, FL</gml:name>
   <countryName>UNITED STATES</countryName>
   <!-- Co-ordinates are available as lng,lat -->

     <gml:Point srsName="">

I had never done anything with XML in python so I figured I would write a function to wrap the API call. A few google searches led me to minidom and the rest was cake. The function takes in an IP address (string) and returns a dictionary with the geo information. I am a python noob and this code feels a little sketchy to me, so any feedback is more than welcome!

import urllib
from xml.dom import minidom

GML_NS = ''

def geo_ip_lookup(ip_address):
    Look up the geo information based on the IP address passed in
    dom = minidom.parse(urllib.urlopen(GEO_IP_LOOKUP_URL % ip_address))
    elem = dom.getElementsByTagName('Hostip')[0]
    location = elem.getElementsByTagNameNS(GML_NS, 'name')[0]',')

        latlong = elem.getElementsByTagNameNS(GML_NS, 'coordinates')[0]',')
        # lat/long isnt always returned
        latlong = None

    return {
            'country_code': elem.getElementsByTagName('countryAbbrev')[0],
            'country_name': elem.getElementsByTagName('countryName')[0],
            'locality': location[0].strip(),
            'region': location[2].strip(),
            'longitude': latlong[0].strip() if latlong else '',
            'latitude': latlong[2].strip() if latlong else ''

Calling it from the interpreter:

>>> geo_ip_lookup('')
{'locality': u'Miami', 'region': u'FL', 'longitude': u'-80.2108', 'latitude': u'25.7757', 'country_code': u'US', 'country_name': u'UNITED STATES'}


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