Django中间件

浏览器发送一个请求到django网站怎么执行:

中间件

  • Django中的中间件是一个轻量级、底层的插件系统,可以介入Django的请求和响应处理过程,修改Django的输入或输出
  • 中间件的设计为开发者提供了一种无侵入式的开发方式,增强了Django框架的健壮性,其它的MVC框架也有这个功能,名称为IoC
  • Django在中间件中预置了六个方法,这六个方法的区别在于不同的阶段执行,对输入或输出进行干预,方法如下
  • 1.初始化:无需任何参数,服务器响应第一个请求的时候调用一次,用于确定是否启用当前中间件
def __init__():
    pass
  • 2.处理请求前:在每个请求上调用,返回None或HttpResponse对象
def process_request(request):
    pass
  • 3.处理视图前:在每个请求上调用,返回None或HttpResponse对象
def process_view(request, view_func, view_args, view_kwargs):
    pass
  • 4.处理模板响应前:在每个请求上调用,返回实现了render方法的响应对象
def process_template_response(request, response):
    pass
  • 5.处理响应后:所有响应返回浏览器之前被调用,在每个请求上调用,返回HttpResponse对象
def process_response(request, response):
    pass
  • 6.异常处理:当视图抛出异常时调用,在每个请求上调用,返回一个HttpResponse对象
def process_exception(request,exception):
    pass
  • 下图描述了六个方法的一次请求响应过程中的阶段

示例

  • 中间件是一个独立的python类,,可以定义这五个方法中的一个或多个
  • 在booktest/目录下创建middleware.py文件,代码如下
#coding=utf-8

class my_mid:
    def __init__(self):
        print '--------------init'
    def process_request(self,request):
        print '--------------request'
    def process_view(self,request, view_func, view_args, view_kwargs):
        print '--------------view'
    def process_template_response(self,request, response):
        print '--------------template'
        return response
    def process_response(self,request, response):
        print '--------------response'
        return response
  • 在test5/settings.py文件中,向MIDDLEWARE_CLASSES项中注册

  • 修改booktest/views.py中视图index
def index(request):
    print '======index======'
    return render(request,'booktest/index.html')
  • 运行服务器,命令行中效果如下图

  • 刷新页面,命令行中效果如下图

异常中间件

  • 在booktest/middleware.py中定义两个异常类如下
class exp1:
    def process_exception(self,request,exception):
        print '--------------exp1'
class exp2:
    def process_exception(self,request,exception):
        print '--------------exp2'
  • 在test5/settings.py文件中,向MIDDLEWARE_CLASSES项中注册

  • 修改booktest/views.py中视图index
def index(request):
    print '======index======'
    raise Exception('自定义异常')
    return render(request,'booktest/index.html')
  • 总结:如果多个中间件中注册了相同的方法,则先注册的后执行

猜你喜欢

转载自blog.csdn.net/weixin_31955923/article/details/80026277