views:

416

answers:

2

How can you detect the country of origin of the users accessing your site?

I'm using Google Analytics on my site and can see that I have users coming from different regions of the world.

But within my application I would like to provide some additional customization based on the country and perhaps the city.

Is it possible to detect this infomation from the browser? This is a Python web application.

+8  A: 

Get the visitor's IP and check it with a geolocation web service (or purchase a geolocation database if you're keen to host that determination in-house).

Alex Martelli
People sure can be premature when marking solutions.
Glenn Maynard
+8  A: 

Grab and gunzip http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz, install the GeoIP-Python package (python-geoip package if you're in Debian or Ubuntu, otherwise install http://geolite.maxmind.com/download/geoip/api/python/GeoIP-Python-1.2.4.tar.gz), and do:

import GeoIP
gi = GeoIP.open("GeoLiteCity.dat", GeoIP.GEOIP_INDEX_CACHE | GeoIP.GEOIP_CHECK_CACHE)
print gi.record_by_name("74.125.67.100") # a www.google.com IP

{'city': 'Mountain View', 'region_name': 'California', 'region': 'CA', 'area_code': 650, 'time_zone': 'America/Los_Angeles', 'longitude': -122.05740356445312, 'country_code3': 'USA', 'latitude': 37.419200897216797, 'postal_code': '94043', 'dma_code': 807, 'country_code': 'US', 'country_name': 'United States'}

The database is free (http://geolite.maxmind.com/download/geoip/database/LICENSE.txt). They do sell it, too; I think that just gets you more frequent updates.

Glenn Maynard
By the way, there's also a country-only database that's much smaller, if that's all you need (http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz). Just change the file over, use GeoIP.GEOIP_STANDARD instead of the flags above, and then call gi.country_code_by_name(ip).
Glenn Maynard
Thanks for the heads up, I've used the maxmind web interface but never noticed that they offer a free database before.
David Caunt