Login

Middleware decoratores for classed based views

Author:
dhke
Posted:
August 27, 2014
Language:
Python
Version:
1.6
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.