首页 技术 正文
技术 2022年11月12日
0 收藏 943 点赞 3,596 浏览 1194 个字

以前接触的是基于函数的保护,网上材料比较多。

但基于类视图的很少。

补上!

Decorating class-based views 装饰类视图

对于类视图的扩展并不局限于使用mixin。你也可以使用装饰器。

Decorating in URLconf URLconf中的装饰器

最简单的装饰类视图的方式是装饰 as_view() 方法返回的结果。最容易装饰的地方是你配置你的视图的地方URLconf中:

from django.contrib.auth.decorators import login_required, permission_requiredfrom django.views.generic import TemplateViewfrom .views import VoteViewurlpatterns = patterns('',    (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),    (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),)

这种方法适用于装饰每个实例的基础。如果你想要视图的每个实例都被装饰, 你需要采用别的方法。

Decorating the class 装饰类

要装饰类视图的每一个实例,你需要装饰类自身的定义。要实现这个目的,你要 应用这个装饰器到类的 dispatch() 方法上。

类方法和独立的函数并不完全一样,因此你不能仅仅应用函数的装饰器 – 你需要先把它转换为一个类方法的装饰器。method_decorator 这个装饰器 能把一个函数装饰器转变为类方法装饰器,因此它就可以被用在实例方法上了。 比如:

from django.contrib.auth.decorators import login_requiredfrom django.utils.decorators import method_decoratorfrom django.views.generic import TemplateViewclass ProtectedView(TemplateView):    template_name = 'secret.html'    @method_decorator(login_required)    def dispatch(self, *args, **kwargs):        return super(ProtectedView, self).dispatch(*args, **kwargs)

在这个例子中, ProtectedView 的每个实例都将拥有登录保护的功能。

Note

method_decorator 方法传递 *args 和 **kwargs 给这个类上的 装饰器。如果你的方法不接受兼容参数集合,它会抛出 TypeError 异常。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297