Wanted a neat way to redirect views based on GeoIP determined criteria, from HTTP_REFERER. Decorator approach seemed the best way to make it straightforward to redirect views.
To use, installed the Max Mind Python GeoIP API : http://www.maxmind.com/app/python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | from django.contrib.gis.utils import GeoIP
from django.shortcuts import render_to_response
from django.shortcuts import HttpResponse
from django.http import HttpResponsePermanentRedirect
class Geo(object):
"""
Return GEOIP dictionary with the following keys:
['city',
'region',
'area_code',
'longitude',
'country_code3',
'latitude',
'postal_code',
'dma_code',
'country_code',
'country_name']
"""
@staticmethod
def city_from_ip(request, ip=None):
"""
If IP is not supplied, get from request
"""
if ip:
city = GeoIP().city(ip)
else:
city = Geo.get_from_request(request)
return HttpResponse(str(city), mimetype="text/json")
@staticmethod
def get_from_request(request):
ip = request.META.get('REMOTE_ADDR')
city = GeoIP().city(ip)
return city
def redirect_if_geoip_matches(redirect_url, *geo_filters):
"""
Checks if the request's HTTP_REFERER GEOIP matches supplied attibutes.
If match, then redirect to specified URL.
"""
if not redirect_url.endswith(r'/'): redirect_url = '%s/' % redirect_url
#if not hasattr(geo_filters, '__iter__'): geo_filters = [geo_filters]
def _dec(view_func):
def _check_referer(request, *args, **kwargs):
geo = Geo.get_from_request(request)
for geo_filter in geo_filters:
for key, val in geo_filter.items():
if not geo.has_key(key):
raise Exception('Invalid GEO key: %s, specified. Valid choices are : %s' % (key, geo.keys()))
if not geo[key] == geo_filter[key]:
is_redirect = False
break
else:
is_redirect = True
break
if is_redirect:
break # OR filter assumed
if is_redirect:
return HttpResponsePermanentRedirect(redirect_url)
else:
return view_func(request, *args, **kwargs)
********** Sample usage *******
@redirect_if_geoip_matches('/geoip/test_redirected_from_EURO',
{'country_code3': 'FRA'},
{'country_code3': 'DEU'},
)
def test_redirect_if_EURO(request):
return HttpResponse('Not EURO')
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
The decorator function is missing a few lines:
At line 67 insert:
#
Please login first before commenting.