了解 Django 1.10 中间件的新风格
Django 1.10 引入了一种新的中间件风格,其中 process_request
和 process_response
合并在一起。
在这种新风格中,中间件是一个可调用的,返回另一个可调用的。嗯,实际上前者是中间件工厂,后者是实际的中间件。
所述中间件工厂需要作为单个参数的下一个中间件在中间件栈,或视图本身达到堆栈的底部时。
所述中间件取请求作为单个参数,总是返回 HttpResponse
。
说明新型中间件如何工作的最好例子可能是展示如何制作向后兼容的中间件 :
class MyMiddleware:
def __init__(self, next_layer=None):
"""We allow next_layer to be None because old-style middlewares
won't accept any argument.
"""
self.get_response = next_layer
def process_request(self, request):
"""Let's handle old-style request processing here, as usual."""
# Do something with request
# Probably return None
# Or return an HttpResponse in some cases
def process_response(self, request, response):
"""Let's handle old-style response processing here, as usual."""
# Do something with response, possibly using request.
return response
def __call__(self, request):
"""Handle new-style middleware here."""
response = self.process_request(request)
if response is None:
# If process_request returned None, we must call the next middleware or
# the view. Note that here, we are sure that self.get_response is not
# None because this method is executed only in new-style middlewares.
response = self.get_response(request)
response = self.process_response(request, response)
return response