1.用途
可以处理Django的请求和响应处理过程,修改Django的输入或输出
2.激活选项设置
添加到Django配置文件中的MIDDLEWARE_CLASSES元组中
例如:
MIDDLEWARE = [
'booktest.MyException.MyException', 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
3.应用下,添加一个独立的类,实现以下方法的至少一种:
_init _:无需任何参数,服务器响应第一个请求的时候调用一次,用于确定是否启用当前中间件
process_request(request):执行视图之前被调用,在每个请求上调用,返回None或HttpResponse对象
process_view(request, view_func, view_args, view_kwargs):调用视图之前被调用,在每个请求上调用,返回None或HttpResponse对象
process_template_response(request, response):在视图刚好执行完毕之后被调用,在每个请求上调用,返回实现了render方法的响应对象
process_response(request, response):所有响应返回浏览器之前被调用,在每个请求上调用,返回HttpResponse对象
process_exception(request,response,exception):当视图抛出异常时调用,在每个请求上调用,返回一个HttpResponse对象
4.示例:
#错误信息如下
# File "C:\python\lib\site-packages\django\core\handlers\wsgi.py", line 151, in __init__
# self.load_middleware()
# File "C:\python\lib\site-packages\django\core\handlers\base.py", line 82, in load_middleware
# mw_instance = middleware(handler)
# TypeError: object() takes no parameters
#出错原始代码:
# from django.http import HttpResponse
# class MyException(object):
# def process_exception(request,response, exception):
# return HttpResponse(exception.message)
# #正确代码1
# class MyException(object):
# def __init__(self, get_response):
# self.get_response = get_response
#
# def __call__(self, request):
# return self.get_response(request)
#
# def process_exception(self, request, exception):
# return HttpResponse(exception)
#正确代码2
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class MyException(MiddlewareMixin):
def process_exception(self, request, exception):
return HttpResponse(exception)
|