• django的cbv模式添加装饰器


    注意

    django的cbv模式添加装饰器需要导入特殊方法 method_decorator


    使用cbv实现视图

    from django.views import View
    from django.utils.decorators import method_decorator
    
    
    class LoginView(View):
    
        def get(self, request):
            return render(request, "login.html")
    
        def post(self, request):
            user = request.POST.get("name")
            pwd = request.POST.get("pwd")
            if user == "safly" and pwd == "123":
                # 登陆成功
                # 写session
                request.session["user2"] = user
                request.session.set_expiry(5)
                return redirect("/index/")
    
    def index(request):
        return render(request,"index.html")

    加在CBV视图的get或post方法上

    # @method_decorator(wrapper, name="get")
    class IndexView(View):
        @method_decorator(wrapper)
        def get(self, request):
            user = request.session.get("user02", "游客")
            return render(request, "index.html", {"user": user})

    加在dispatch方法上(某些特殊装饰器只能加在dispatch上,例如csrf认证)

    # @method_decorator(wrapper, name="get")
    class IndexView(View):
        ## 这么写所有的请求方法都要做登录校验
        @method_decorator(wrapper)
        def dispatch(self, request, *args, **kwargs):
            return super(IndexView,self).dispatch(request,*args,**kwargs)
    
        # @method_decorator(wrapper)
        def get(self, request):
            user = request.session.get("user04", "游客")
            return render(request, "index.html", {"user": user})
    正常加装饰器

    备注:

    csrf_protect,为当前函数强制设置防跨站请求伪造功能,即便settings中没有设置全局中间件。

    csrf_exempt,取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件

    from django.views.decorators.csrf import csrf_exempt, csrf_protect
    
    
    class HomeView(View):
    
        @method_decorator(csrf_exempt)
        def dispatch(self, request, *args, **kwargs):
            return super(HomeView, self).dispatch(request, *args, **kwargs)
    
        def get(self, request):
            return render(request, "home.html")
    
        def post(self, request):
            print("Home View POST method...")
            return redirect("/index/")
    csrf添加装饰器

     

  • 相关阅读:
    fio工具讲解
    flask迁移数据库报错
    base64编码
    OpenStack学习笔记,未完待续
    docker运行报错
    centos搭建SVN服务器并实现自动同步至web目录 (必定安装成功)
    centos/linux 源码安装mysql详细记录
    centos7.7安装php7.3的lnmp环境和composer详细步骤
    laravel-admin使用ueditor重命名图片名称问题
    nginx 图片防盗链 设置
  • 原文地址:https://www.cnblogs.com/Sakurarain/p/9249597.html
Copyright © 2020-2023  润新知