Django-Cookie与装饰器

来源:互联网 发布:暗黑2 1.13 完美 mac 编辑:程序博客网 时间:2024/05/16 07:04

对于一些常常需要判断是否有登录的情况,我们每次都需要用拿到Cookie进行if语句进行判断,不免麻烦,此时我们可以使用之前学习的装饰器功能,定义一个装饰器来统一判断。

FBV与装饰器

# 装饰器def auth(func):    def wrapper(request,*args,**kwargs):        name = request.COOKIE.get("xxx")        if not name:            return redirect("/xxx/")        return func()    return wrapper# 在需要进行Cookie判断的时候使用@authdef main(request):    return render(request,"main.html")

CBV与装饰器

from django.utils.decorators import method_decoratorfrom django.views import View# name='dispatch'表示在dispatch方法中进行Cookie判断@method_decorator(auth,name='dispatch')class Main(View):    def get(self,request):        pass    def post(self,request):        return render(request,"main.html")

在类名中添加装饰器,表示该类下调用所有方法都要认证,若只需要在get或post方法时认证,只需在该方法添加method_decorator装饰即可。