Skip to content

Instantly share code, notes, and snippets.

@Racum
Created June 6, 2013 17:59
Show Gist options
  • Save Racum/5723529 to your computer and use it in GitHub Desktop.
Save Racum/5723529 to your computer and use it in GitHub Desktop.
Using pygeoip to choose a country from a list if matches.
# $ pip install pygeoip
# $ pip install requests
# $ wget -N http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
# $ gunzip GeoIP.dat.gz
import pygeoip
import requests # Just for hiting httplib.
# Example or supported countries:
COUNTRIES = ('br', 'mx', 'cl', 'ar')
gi = pygeoip.GeoIP('GeoIP.dat', pygeoip.MEMORY_CACHE)
# Hiting httplib just for local test.
# In case of Django, look for request.META['REMOTE_ADDR']:
response = requests.get('http://httpbin.org/ip')
ip = response.json()['origin']
country_code = gi.country_code_by_addr(ip).lower()
if country_code in COUNTRIES:
print 'Detected country code as %s.' % country_code
else:
print 'Country not supported.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment