Django views 中的装饰器

关于装饰器

示例:
有返回值的装饰器:判断用户是否登录,如果登录继续执行函数,否则跳回登录界面

def auth(func):
    def inner(request, *args, **kwargs):
        username = request.COOKIES.get('username')
        if not username:
            # 如果无法获取 'username' COOKIES,就跳转到 '/login.html'
            return redirect('/login.html')
        # 原函数执行前
        res = func(request, *args, **kwargs)
        # 原函数执行后
        return res
    return inner

FBV:

直接在需要装饰到函数上面加上@auth

@auth
def index(request):
    return render(request, 'index.html')

CBV:

关于 CBV

只需要给部分方法加上装饰器
from django import views
from django.utils.decorators import method_decorator

class Order(views.View):

    @method_decorator(auth)
    def get(self,reqeust):
        v = reqeust.COOKIES.get('username')
        return render(reqeust,'index.html',{'current_user': v})

    def post(self,reqeust):
        v = reqeust.COOKIES.get('username')
        return render(reqeust,'index.html',{'current_user': v})
需要给所有方法加上装饰器

通过 dispatch 实现

from django import views
from django.utils.decorators import method_decorator

class Order(views.View):

    @method_decorator(auth)
    def dispatch(self, request, *args, **kwargs):
        return super(Order,self).dispatch(request, *args, **kwargs)

    def get(self,reqeust):
        v = reqeust.COOKIES.get('username')
        return render(reqeust,'index.html',{'current_user': v})

    def post(self,reqeust):
        v = reqeust.COOKIES.get('username')
        return render(reqeust,'index.html',{'current_user': v})

直接在类上给 dispatch 添加装饰器

from django import views
from django.utils.decorators import method_decorator

@method_decorator(auth,name='dispatch')
class Order(views.View):

    def get(self,reqeust):
        v = reqeust.COOKIES.get('username')
        return render(reqeust,'index.html',{'current_user': v})

    def post(self,reqeust):
        v = reqeust.COOKIES.get('username')
        return render(reqeust,'index.html',{'current_user': v})

原文地址:https://www.cnblogs.com/dbf-/p/10926124.html

时间: 2024-07-31 00:10:07

Django views 中的装饰器的相关文章

@修饰符--python中的装饰器

http://blog.csdn.net/shangzhihaohao/article/details/6928808 装饰器模式可以在不影响其他对象的情况下,以动态.透明的方式给单个对象添加职责,也能够处理那些可以撤销的职责.经常用于日志记录.性能测试等场合. 想象一下这个很常见的场景,你写了一个方法只提供给以登陆的用户访问(事实上我也是通过django的@login_required才了解到@修饰符的),你可以写以下代码: 这当然没什么问题,但是你又写了一个方法B,也要求只有登录用户可以访问

二十五:视图之类视图中使用装饰器

对于url的保护,一般是通过装饰器实现,如:某个页面需要登录后才能访问 函数视图实现 from flask import Flask, render_template, requestfrom functools import wrapsapp = Flask(__name__)def login_required(func): @wraps(func) def wrapper(*args, **kwargs): username = request.args.get('username') r

Python 中实现装饰器时使用 @functools.wraps 的理由

Python 中使用装饰器对在运行期对函数进行一些外部功能的扩展.但是在使用过程中,由于装饰器的加入导致解释器认为函数本身发生了改变,在某些情况下--比如测试时--会导致一些问题.Python 通过 functool.wraps 为我们解决了这个问题:在编写装饰器时,在实现前加入 @functools.wraps(func) 可以保证装饰器不会对被装饰函数造成影响.比如,在 Flask 中,我们要自己重写 login_required 装饰器,但不想影响被装饰器装饰的方法,则 login_req

自己编写一个装饰器中的装饰器函数

看了"大道曙光"的<探究functools模块wraps装饰器的用途>的文章.基本上弄清了wraps的工作原理,为了检验一下自己理解的程度,于是动手写一个类似的 wraps函数,请大家指教. #!/usr/bin/env python # -*- coding: utf-8 -*- #filename : mywrapper.py #date: 2017-06-02 ''' wrapper function by my code.''' import functools i

Typescript中的装饰器原理

Typescript中的装饰器原理 1.小原理 因为react中的高阶组件本质上是个高阶函数的调用, 所以高阶组件的使用,我们既可以使用函数式方法调用,也可以使用装饰器. 也就是说,装饰器的本质就是一个高阶函数, 就是利用TypeScript的弱类型特性和装饰器特性,实现了一个加强版. 2.以一个例子来讲 //定义一个装饰器函数decTest function decTest(constructor: Function) { console.log(constructor("hello!&quo

【react】---react中使用装饰器(高阶组件的升级用法)

一.creact-react-app中使用装饰器 运行 npm run eject 可以让由create-react-app创建的项目的配置项暴露出来 此时,项目中多了一个config文件,并且各个配置文件已经暴露出来了.(运行npm run eject之前,保证本地没有待提交到git的文件) 安装babel插件npm install --save-dev @babel/plugin-proposal-decorators 修改package.json文件的babel配置项 "babel&quo

Angular中的装饰器

Angualr中的装饰器是一个函数,它将元数据添加到类.类成员(属性.方法)和函数参数 用法:要想用装饰器,把它放到被装饰对象的上面或做左面 1.类装饰器: 类装饰器应用于类构造函数,可以用来监控.修改或替换类定义 类装饰器表达式会在运行时当作函数被调用,类的构造函数作为唯一的参数 @Component 标记类作为组件并收集组件配置元数据(继承Directive) @Directive 标记类作为指令并收集组件配置元数据 声明当前类时一个指令,并提供关于该指令的元数据 @Pipc 声明当前类是一

如何理解python中的装饰器, 这篇文章就够了!

1. python中的函数 理解裝飾器之前先要理解閉包, python中閉包的出現是因爲函數在python中也是一個對象, 也可以被引用, 然後調用, 比如 def log(): print('我是一些log信息') if __name__ == '__main__': print(type(log)) log_func = log log_func() 執行結果如下 <class 'function'> 我是一些log信息 可以看到log函數是一個對象, 可以被賦值給log_func, lo

Django中decorators装饰器的使用

1.CBV实现的登录视图 class LoginView(View): def get(self, request): """ 处理GET请求 """ return render(request, 'login.html') def post(self, request): """ 处理POST请求 """ user = request.POST.get('user') pwd = re