Search code examples
pythonweb-applications

How to detect the country and city of a user accessing your site?


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.


Solution

  • 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.