Redirect view based on GEO

 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. HttpResponseRedirectView - Redirect to a view by adamlofts 5 years, 8 months ago
  2. View Redirect Decorators by bryanpieper 3 years, 9 months ago
  3. Internet Explorer Redirect Decorator by johnboxall 5 years, 6 months ago
  4. login_required decorator that doesn't redirect by brutasse 3 years, 2 months ago
  5. Alternative to Class Based Views by sleepycal 1 year, 7 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

#

(Forgotten your password?)