Login

BeforeFilter Middleware

Author:
david
Posted:
February 3, 2009
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

Expanded version of snippet 715 to be more flexible.

Updates:

  • 2009-04-24: Multiple filters now work correctly
  • 2009-03-22: Fixed bug
  • 2009-02-03: Simplified process.
 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
import sys

class BeforeFilter(object):
    """
    Middleware component for performing actions before
    calling views.

    To use, define BEFORE_FILTER in your application's views.py.
    BEFORE_FILTER should be a dictionary mapping a filter function
    to a list/tuple of view functions::

        BEFORE_FILTER = {'check_trailing_slash': ('index',
                                                  'detail')}

    To have *all* view functions filtered, simply leave the tuple
    blank::

        BEFORE_FILTER = {'authenticate': ()}

    To exclude a view from being filtered prefix it with dash::

        BEFORE_FILTER = {'authenticate': ('-index',
                                          '-detail')}

    If you require filters to be applied in a specific order, use Django's
    SortedDict::

        from django.utils.datastructures import SortedDict

        BEFORE_FILTER = SortedDict()
        BEFORE_FILTER['authenticate'] = ('-index', '-detail')
        BEFORE_FILTER['get_messages'] = ()

    """
    def __init__(self):
        self.setting = 'BEFORE_FILTER'
        self.filters = []

    def _call_filters(self, request, view, args, kwargs):
        response = None
        for f in self.filters:
            response = f(request, view, args, kwargs)
            if response and response.has_header('location'):
                return response
        self.filters = []
        return response

    def process_view(self, request, view, args, kwargs):
        module = sys.modules[view.__module__]
        if hasattr(module, self.setting):
            for func, views in getattr(module, self.setting).items():
                exclude = '-%s' % view.func_name
                if not views or view.func_name in views or views and \
                    exclude not in views:
                    if hasattr(module, func):
                        if getattr(module, func) not in self.filters:
                            self.filters.append(getattr(module, func))
        if self.filters:
            return self._call_filters(request, view, args, kwargs)
        return None

More like this

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

Comments

Please login first before commenting.