Jon Atkinson

I'm a technologist, with a long and varied history in high-end technical delivery and infrastructure management. I'm particularly interested in managing software teams, rapid application development, and scalability challenges.

Obtaining GeoIP location with YQL using Python

20th April 2010

I've a few projects coming up for 84labs which required location awareness. Location awareness works great with any recent phone, but for traditional clients, I needed to fall-back to obtaining the location from the client's IP address.

There is an excellent free IP location database hosted on datatables.org, which offered the easiest way to get the data which I needed. This meant using YQL, which I haven't used before; YQL is "an expressive SQL-like language that lets you query, filter, and join data across Web services".

So here is the code. I was using Python, Django and Python YQL module, but the same query presumably works with any language you choose. I've removed a lot of exception handling for clarity.

# Get the current user's IP address.
client_ip_address = request.META['REMOTE_ADDR']

# Create a YQL public query object.
y = yql.Public()

# Build the query.
query = 'USE "http://www.datatables.org/iplocation/ip.location.xml" AS ip.location; select * from geo.places where woeid in (select place.woeid from flickr.places where (lat,lon) in(select Latitude,Longitude from ip.location where ip="%s"))' % client_ip_address;

# Execute the query.
result = y.execute(query)

# ... et voila.
ip_place_name = result.rows['locality1']['content']
ip_location = result.rows['centroid']</code>

That's it. The query just performs a simple select against the 'iplocation' database, then retrieves the latitude and longitude from the flickr.places database (flickr.places is part of the standard YQL set of databases, which is why we don't need a specific USE statement to be able to access it).