Login

Redirect view based on GEO

Author:
jorjun
Posted:
August 7, 2009
Language:
Python
Version:
1.1
Score:
2 (after 2 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

sbaechler (on July 27, 2012):

The decorator function is missing a few lines:

At line 67 insert:

    _check_referer.__doc__ = view_func.__doc__
    _check_referer.__dict__ = view_func.__dict__
    return _check_referer
return _dec

#

Please login first before commenting.