zoukankan      html  css  js  c++  java
  • 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})
    
  • 相关阅读:
    PAT 00-自测1. 打印沙漏(20)
    js Ajax
    c语言算法实现
    解决python for vs在vs中无法使用中文
    python排序算法实现:
    2014-4-27 心情
    Sdut 2416 Fruit Ninja II(山东省第三届ACM省赛 J 题)(解析几何)
    Poj 1061 青蛙的约会(扩展欧几里得)
    hrbust 1328 相等的最小公倍数(数论)
    hdu 1286 找新朋友 (欧拉函数)
  • 原文地址:https://www.cnblogs.com/dbf-/p/10926124.html
Copyright © 2011-2022 走看看