Skip to content

Instantly share code, notes, and snippets.

@matthieucan
Last active August 29, 2015 14:03
Show Gist options
  • Save matthieucan/540ca40d5e4d2c1783ba to your computer and use it in GitHub Desktop.
Save matthieucan/540ca40d5e4d2c1783ba to your computer and use it in GitHub Desktop.
Django template filter to transform an IP address into GPS coordinates (for e.g. OpenLayers.js)
# Copyright 2014 Matthieu Caneill
# Consider this equivalent to public domain, feel free to use it the way you want.
# pip install python-geoip
# pip install python-geoip-geolite2
import socket
from geoip import geolite2
@register.filter("locateip")
def locateip(value):
def is_legal_ip(ip):
try:
socket.inet_pton(socket.AF_INET, address)
except Exception:
try:
socket.inet_pton(socket.AF_INET6, address)
except Exception:
return False
return True
if not is_legal_ip(value):
try:
value = socket.gethostbyname(value)
except Exception:
return None
try:
match = geolite2.lookup(value)
lat, lon = match.location
except Exception as e:
print value, e
return None
return '%s,%s' % (lon, lat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment