zoukankan      html  css  js  c++  java
  • Django:(05)类视图,装饰器和中间件

    一、类视图的定义和使用

    在Django中还可以通过类来定义一个视图,称为类视图

    定义一个类视图:定义一个类,需继承 Django 提供的 View 类 。

    from django.views.generic import View
    
     class TestView(View):
    
         def get(self, request):
             """get请求"""
             return render(request, 'index.html')
    
         def post(self, request):
             """post请求"""
             # 代码略
             return HttpResponse('操作结果')
    

    路由配置:调用类视图的 as_view() 方法

     urlpatterns = [
         ...
         url(r'^Test$', views.PostView.as_view()),
     ]
    

    as_view()的作用是按照不同请求方式调用不同请求方法,详情查看 as_view() 方法源码,以及其内部调用的 dispatch()

    二、类视图继承扩展类

    定义的扩展父类名称通常以Mixin结尾,类视图可以直接通过多继承,继承他们的方法。

    • ListModelMixin 查询多条数据(列表数据)

    • CreateModelMixin 新增一条数据

    • RetrieveModelMixin 查询一条数据

    • UpdateModelMixin 修改一条数据

    • DestroyModelMixin 删改一条数据

    这些 Mixin 类分别提供了不同的类视图方法{{TODO:后续补充详情}})

    class DepartmentView(CreateModelMixin, ListModelMixin, View):
        """
        同时继承两个扩展类
        """
        def get(self, request):
            # 复用父类ListModelMixin的list方法
            return self.list(request)    
    
        def post(self, request):
            # 复用父类CreateModelMixin的create方法
            return self.create(request) 
    
    class EmployeeView(CreateModelMixin, View):
        """
        继承CreateModelMixin扩展类
        """
        def post(self, request):
            # 复用父类ListModelMixin的list方法
            return self.create(request)
    

    三、为视图添加装饰器

    装饰器:不在改变原有函数的前提下,在函数调用之前或之后执行额外的操作

    1、准备一个装饰器

    def check_ip(view_fun):
         """装饰器:禁止黑名单ip访问"""
         def wrapper(request, *args, **kwargs):
             # 在视图函数执行前做额外的操作:
             # 禁止ip黑名单访问
             IP = request.META.get('REMOTE_ADDR')
             if IP in ['192.168.210.160']:
                 return HttpResponse('IP禁止访问')
             return view_fun(request, *args, **kwargs)
         return wrapper
    

    2、不能直接使用我们上面的装饰器(缺少self参数)

    需要使用method_decorator 装饰器,函数装饰器补充第一个self参数,使它可以应用到类的方法中。

    @method_decorator(check_ip)
    

    3、给类视图的特定的方法添加装饰器

    class PostView(View):
    
        @method_decorator(check_ip)
        def post(self, request):
            return HttpResponse('处理发帖操作')
    

    4、给类视图的所有方法应用装饰器:

    给 dispatch 方法加上@method_decorator(check_ip),就能给给类视图的所有方法应用装饰器:

    class PostView(View):
    
        @method_decorator(check_ip)
        def dispatch(self, request, *args, **kwargs):
            return super().dispatch(request, *args, **kwargs)
    

    5、另一种方式:

    在类上面添加装饰器,指定对哪个方法进行装饰 :@method_decorator(装饰器名, name='视图方法名')

    @method_decorator(check_ip, name='get')
    class PostView(View):
    
        def get(self, request):
            return render(request, 'index.html')
    
        def post(self, request):
            return HttpResponse('操作结果')
    

    四、Django中间件

    一个轻量级、底层的插件系统,用于在视图函数调用之前或之后执行额外操作,在全局上修改Django的输入或输出。

    方法名 作用 返回值
    __init__(self, get_response=None) 服务器启动(重启)时执行一次
    process_request(self, request) 在视图执行之前调用 返回 None: 会执行视图;返回 HttpResponse: 不会再执行视图
    process_response(self, request, response) 在视图执行完之后调用 必须返回HttpResponse对象

    ![image](file:///E:/05%20django/0921D44-01%20%E9%A1%B9%E7%9B%AE%E6%90%AD%E5%BB%BA%20%E9%85%8D%E7%BD%AE/django%E8%AE%B2%E4%B9%89/imgs/django-062.png)

    1、定义中间件

    通过继承Django的MiddlewareMixin扩展类实现

    class MyMiddleware(MiddlewareMixin):
        def process_request(self, request):
            print('before 视图')
    
        def process_response(self, request, response):
            print('after 视图')
            return response   	# 必须要有返回值
    

    process_request():可以返回None或者response对象,如果返回response对象,则视图函数就不会再执行了

    2、在settings文件中配置

    MIDDLEWARE = [
         'middlewares.MyMiddleware',  # 注册中间件
     ]
    

    3、多个中间件的执行顺序

    • 对于视图之前执行的 process_request 方法,先 注册的中间件先执行
    • 对于视图之后执行的 process_response 方法,后 注册的中间件先执行

    要注意多个中间件之间的依赖关系, 被依赖的中间件要声明在前面

  • 相关阅读:
    wrap,wrapall,wrapinner的区别:
    jqueryappend和appendTo的区别
    《Nagios系统监控实践》一书出版
    基于Python的密码生成程序的优化
    Puppet学习:pp文件权限问题
    依然看不清
    免费编程中文书籍索引
    Linux批量修改指定目录下的文件或文件夹权限
    puppet学习:文件夹权限的问题
    Zabbix探索:Zabbix API使用时的错误1
  • 原文地址:https://www.cnblogs.com/mzfly/p/9978612.html
Copyright © 2011-2022 走看看