Other approach of making middleware (by decorators)

 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
from functools import wraps

def RequestMiddleware(middleware_func):
    """ RequestMiddleware """

    @wraps(middleware_func)
    def middleware(view_func):
        """ middleware """

        @wraps(view_func)
        def new_view_func(request, *args, **kwargs ):
            """ new_view_func """

            middleware_func(request, *args, **kwargs)

            return view_func(request, *args, **kwargs)
        return new_view_func
    return middleware


def ResponseMiddleware(middleware_func):
    """ ResponseMiddleware """

    @wraps(middleware_func)
    def middleware(view_func):
        """ middleware """

        @wraps(view_func)
        def new_view_func(request, *args, **kwargs ):
            """ new_view_func """

            response = view_func(request, *args, **kwargs)

            middleware_func(request, response, *args, **kwargs)

            return response
        return new_view_func
    return middleware


def ExceptionMiddleware(middleware_func):
    """ ExceptionMiddleware """

    @wraps(middleware_func)
    def middleware(view_func):
        """ middleware """

        @wraps(view_func)
        def new_view_func(request, *args, **kwargs ):
            """ new_view_func """

            try:
                response = view_func(request, *args, **kwargs)
            except Exception, e:
                response = middleware_func(request, e, *args, **kwargs)

            if response is None:
                raise

            return response
        return new_view_func
    return middleware

More like this

  1. Owner required decorator by polarbear 5 years, 9 months ago
  2. Format transition middleware by limodou 7 years, 1 month ago
  3. PK->objects in view signature by AdamKG 6 years ago
  4. object-oriented generic views by carljm 5 years, 7 months ago
  5. Django JSONP Decorator by cominatchu 3 years, 6 months ago

Comments

(Forgotten your password?)