FBV Decorator:
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
How to use:
Add @auth to the function
CBV Decorator:
The first way: Using Django's own tools
def auth (func): #装饰器函数 authenticates a cookie def inner (request, *args, **kwargs): v = Request. Cookies.get (' username ') if not V: return redirect ('/log/') return func (Request, *args, **kwargs) Return innerfrom Django Import views from django.utils.decorators import method_decorator #导入django自带的工具class Auth (views. View): @method_decorator (auth) #利用django自带工具 Import the authentication function adorner for authentication, flexibly placed under any function requiring authentication 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})
The second way:
From the Django Import viewsfrom django.utils.decorators import method_decoratorclass Auth (views. View): @method_decorator (auth) #将装饰器放在父类方法上 so that all the methods under this class are decorated with decorators, not all written on the function def dispatch (self, request , *args, **kwargs): return Super (Auth, self). Dispatch (self, request, *args, **kwargs) def get (self, request): C5/>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})
The Third Way:
From Django Import viewsfrom django.utils.decorators import method_decorator@method_decorator (auth, Name= ' dispatch ') #将装饰器直接装饰在类上面, the Diapatch method, which is decorated in the parent class with name, also implements the decorative effect class Auth (views) of all the methods in the class. 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 Program Case Series-10 verification Adorner