python - How to properly define a middleware class in Django v1.11? -
i'm working on django (v1.11) project , need provide middleware functionality site. version of django modify old middleware_classes setting described in docs:
a new style of middleware introduced use new
middlewaresetting.
however, i can't understand how new middleware works. after reading middleware's documentation come following conclusion:
class foomiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_template_response(self, request, response): # here return response i thought it'll work, unfortunately code above doesn't work , ignored django (without error!).
when following:
class foomiddleware(object): def process_template_response(self, request, response): # here return response ...an error occured (because __init__ method of object class has no arguments):
typeerror: object() takes no parameters
when change code follows everything works:
from django.utils.deprecation import middlewaremixin class foomiddleware(middlewaremixin): def process_response(self, request, response): # here return response but! middlewaremixin related deprecation utils , used compatibility purposes:
django provides
django.utils.deprecation.middlewaremixinease creating middleware classes compatible bothmiddleware, oldmiddleware_classes.
question: how define middleware class in django v1.11?
defining process_template_response useful if response instance has render() method. if not, should move custom code __call__ method.
class foomiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # here return response wiki
Comments
Post a Comment