Login

Middleware decoratores for classed based views

Author:
dhke
Posted:
August 27, 2014
Language:
Python
Version:
1.6
Tags:
middleware decorator class-based-views
Score:
0 (after 0 ratings)

Decorators to attach middleware to class based views w/o arguments.

 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
def middleware_on_class_with_args(middleware):
	"""
		Same as ``middleware_on_class`` but returns a function that accepts
		additional arguments to be passed to middleware

		Use as:
		@middleware_on_class_with_args(MiddlewareClass)(arg0, kwarg=x)
		class View:
			...

		The decorated class is modified in place.
	"""
	def wrapper_builder(*args, **kwargs):
		def decorator(cls):
			dispatch = cls.dispatch

			@wraps(dispatch)
			@method_decorator(decorator_from_middleware_with_args(middleware)(*args, **kwargs))
			def wrapper(self, *args, **kwargs):
				return dispatch(self, *args, **kwargs)

			cls.dispatch = wrapper
			return cls
		return decorator
	return wrapper_builder


def middleware_on_class(middleware):
	"""
		A class decorator to attach the designated middleware to a class-based view.

		Use as
		@middleware_on_class(MiddlewareClass)
		class View:
			...

		Takes a single parameter, ``MiddlewareClass'', which must
		be a django middleware class (not an instance).

		The decorated class is modified in place.
	"""
	def decorator(cls):
		dispatch = cls.dispatch

		@wraps(dispatch)
		@method_decorator(decorator_from_middleware(middleware))
		def wrapper(self, *args, **kwargs):
			return dispatch(self, *args, **kwargs)

		cls.dispatch = wrapper
		return cls

More like this

  1. Class based view decorator by robcharlwood 4 years ago
  2. Decorate class-based views with regular decorators by jeffheard 8 months ago
  3. LoginRequired class-based view decorator by mjumbe 4 years, 1 month ago
  4. middleware for user_passes_test by gsf0 5 years, 10 months ago
  5. Class-based process form view. by I159 3 years, 8 months ago

Comments

Please login first before commenting.