Django-website 程序案例系列-10 验证装饰器
Posted 划得戳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django-website 程序案例系列-10 验证装饰器相关的知识,希望对你有一定的参考价值。
FBV装饰器:
def auth(func): #装饰器函数 def inner(request, *args, **kwargs): v = request.COOKIES.get(‘username‘) if not v: return redirect(‘/log/‘) return func(request, *args, **kwargs) return inner
使用方法:
在函数上加上@auth
CBV装饰器:
第一种方式:利用django自带的工具
def auth(func): #装饰器函数 对cookie进行认证 def inner(request, *args, **kwargs): v = request.COOKIES.get(‘username‘) if not v: return redirect(‘/log/‘) return func(request, *args, **kwargs) return inner from django import views from django.utils.decorators import method_decorator #导入django自带的工具 class Auth(views.View): @method_decorator(auth) #利用django自带工具 导入认证函数装饰器进行认证,灵活的放在任意需要认证的函数下面 def get(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v}) def post(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v})
第二种方式:
from django import views from django.utils.decorators import method_decorator class Auth(views.View): @method_decorator(auth) #将装饰器放在父类方法上 这样该类下所有方法都被装饰上了装饰器,不用一一在写在函数上面 def dispatch(self, request, *args, **kwargs): return super(Auth, self).dispatch(self, request, *args, **kwargs) def get(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v}) def post(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v})
第三种方式:
from django import views from django.utils.decorators import method_decorator @method_decorator(auth, name=‘dispatch‘) #将装饰器直接装饰在类上面,在用name指定装饰在父类的diapatch方法上,这样也就实现了类里面所有方法的装饰效果 class Auth(views.View): def get(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v}) def post(self, request): v = request.COOKIES.get(‘username‘) return render(request, ‘user_list.html‘, {‘current_user‘: v})
以上是关于Django-website 程序案例系列-10 验证装饰器的主要内容,如果未能解决你的问题,请参考以下文章
Django-website 程序案例系列-6 html模板文件详解
Django-website 程序案例系列-16 modle.form(表单验证)
Django-website 程序案例系列-4 ORM数据库操作