zoukankan      html  css  js  c++  java
  • Django2.X中的中间件

    相比Django1.X中间件,Django2.X中的中间件使用方法做了修改。

    1.定义中间件需要继承MiddlewareMixin类:

    from django.utils.deprecation import MiddlewareMixin
    
    class 中间件类名(MiddlewareMixin):
        pass

    2.中间件类中的__init__方法看 MiddlewareMixin 的源码是需要传入两个参数

    class MiddlewareMixin:
        def __init__(self, get_response=None):
            self.get_response = get_response
            super().__init__()
    
        def __call__(self, request):
            response = None
            if hasattr(self, 'process_request'):
                response = self.process_request(request)
            response = response or self.get_response(request)
            if hasattr(self, 'process_response'):
                response = self.process_response(request, response)
            return response
    MiddlewareMixin
        def __init__(self,request=None):
            super().__init__()
            print('---init---')

      凭自己的理解重写__init__方法后报服务器500错误,Django的错误是这样的

       没有时间做进一步的深入了解,将__init__方法注释后没有报错了。有朋友或大牛知道处理方法,可以评论告知一下,谢谢!

    3.视图处理异常可以直接在中间件类中定义一个方法来实现

       如果处理异常需要多个处理方式,可以和Django1.X中一样,定义多个中间件类,在项目settings中注册。

     

       效果和Django1.X中一样:

  • 相关阅读:
    caffe:使用C++来提取任意一张图片的特征(从内存读取数据)
    python:控制鼠标和键盘
    .dll 文件编写和使用
    python:打包成exe程序
    python:小乌龟turtle
    python:input()和raw_input()
    C++:哈希
    C++:线程(std::thread)
    GitHub:Git的使用
    链表
  • 原文地址:https://www.cnblogs.com/zzmx0/p/12826511.html
Copyright © 2011-2022 走看看