Created
June 6, 2013 17:59
-
-
Save Racum/5723529 to your computer and use it in GitHub Desktop.
Using pygeoip to choose a country from a list if matches.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# $ 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