如何在 Django v1.11 中正确定义中间件 class?
How to properly define a middleware class in Django v1.11?
我正在处理 Django (v1.11) 项目,需要为站点提供一些中间件功能。此版本的 Django 修改旧 MIDDLEWARE_CLASSES
设置,如 docs:
中所述
A new style of middleware was introduced for use with the new
MIDDLEWARE
setting.
但是,我无法理解 NEW 中间件的工作原理。阅读中间件的文档后,我得出以下结论:
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):
# do something here
return response
我认为它会起作用,但不幸的是上面的代码不起作用并且被 Django 完全忽略(没有任何错误!).
当我执行以下操作时:
class FooMiddleware(object):
def process_template_response(self, request, response):
# do something here
return response
...发生错误(因为object
class 的__init__
方法没有参数):
TypeError: object() takes no parameters
当我按如下方式更改代码时 一切正常:
from django.utils.deprecation import MiddlewareMixin
class FooMiddleware(MiddlewareMixin):
def process_response(self, request, response):
# do something here
return response
但是! MiddlewareMixin
与 deprecation
实用程序相关并用于兼容性目的:
Django provides django.utils.deprecation.MiddlewareMixin
to ease
creating middleware classes that are compatible with both MIDDLEWARE
and the old MIDDLEWARE_CLASSES
.
问题:如何在 Django v1.11 中正确定义中间件class?
定义 process_template_response
仅当您的响应实例具有 render()
方法时才有用。如果没有,您应该将自定义代码移至 __call__
方法中。
class FooMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
# Do something here
return response
我正在处理 Django (v1.11) 项目,需要为站点提供一些中间件功能。此版本的 Django 修改旧 MIDDLEWARE_CLASSES
设置,如 docs:
A new style of middleware was introduced for use with the new
MIDDLEWARE
setting.
但是,我无法理解 NEW 中间件的工作原理。阅读中间件的文档后,我得出以下结论:
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):
# do something here
return response
我认为它会起作用,但不幸的是上面的代码不起作用并且被 Django 完全忽略(没有任何错误!).
当我执行以下操作时:
class FooMiddleware(object):
def process_template_response(self, request, response):
# do something here
return response
...发生错误(因为object
class 的__init__
方法没有参数):
TypeError: object() takes no parameters
当我按如下方式更改代码时 一切正常:
from django.utils.deprecation import MiddlewareMixin
class FooMiddleware(MiddlewareMixin):
def process_response(self, request, response):
# do something here
return response
但是! MiddlewareMixin
与 deprecation
实用程序相关并用于兼容性目的:
Django provides
django.utils.deprecation.MiddlewareMixin
to ease creating middleware classes that are compatible with bothMIDDLEWARE
and the oldMIDDLEWARE_CLASSES
.
问题:如何在 Django v1.11 中正确定义中间件class?
定义 process_template_response
仅当您的响应实例具有 render()
方法时才有用。如果没有,您应该将自定义代码移至 __call__
方法中。
class FooMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
# Do something here
return response