CBV如何加装饰器

# 先导包:from django.utils.decorators import method_decorator
# 方式一,加在某个具体的方法上,格式:@method_decorator(装饰器名字)
# 方式二,加在类上,格式:@method_decorator(装饰器名字,name='给某个方法加')
# 方式三,写一个dispatch方法,加在其上,该类里的方法都会被装饰,格式:@method_decorator(login_auth)

CBV加装饰器实例

from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from functools import wraps

# 给CBV加装饰器,需要导入以下模块
from django.utils.decorators import method_decorator

# Create your views here.
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        if username == 'jason' and pwd == '123':
            request.session['name'] = 'jason'
            return redirect('/home/')
    return render(request, 'login.html')


def login_auth(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        if request.session.get('name'):
            return func(request, *args, **kwargs)
        return redirect('/login/')
    return inner


# 第二种加装饰器的方法,@method_decorator(装饰器名字,name='给某个方法加')
# @method_decorator(login_auth, name='get')
class MyHome(View):
    # 第三种加装饰器的方法,该类里的方法都会被装饰
    @method_decorator(login_auth)
    def dispatch(self, request, *args, **kwargs):
        super().dispatch(request, *args, **kwargs)

    # 第一种加装饰器的方法,@method_decorator(装饰器名字)
    # @method_decorator(login_auth)
    def get(self, request):
        """
        处理get请求
        """
        return HttpResponse('get')

    def post(self, request):
        """
        处理post请求
        """
        return HttpResponse('post')
posted on 2022-12-10 17:13  wfw001  阅读(43)  评论(0编辑  收藏  举报