Improved GeoIP Lookup Function in Python
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" : "74.125.45.100",
"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('81.83.5.11')
{'locality': u'Gent', 'region': u'Oost-Vlaanderen', 'longitude': u'3.7167', 'latitude': u'51.05', 'country_code': u'BE', 'country_name': u'Belgium'}
>>>
JSON FTW!
blog comments powered by Disqus