1. 程式人生 > >Django自定義裝飾器

Django自定義裝飾器

prot clas bject ora isp ESS method elf dispatch

裝飾器模板:

def decorator(func):
    def wrapper(*args,**kwargs):
        return func(*args,**kwargs)  
    return wrapper

  

裝飾器應用:

def log_in(func):
    ‘‘‘身份認證裝飾器,
    :param func:
    :return:
    ‘‘‘
    def wrapper(request,*args,**kwargs):
        if not request.session.get("is_login"):
            return redirect("/book/login/")
        return  func(request,*args, **kwargs)
    return wrapper

@log_in #author=log_in(author) 
def author(request):
    author_list = models.Author.objects.all()
    return render(request, "author.html", {"authorList": author_list})

  

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

class ProtectedView(TemplateView):
    template_name = ‘secret.html‘

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ProtectedView, self).dispatch(*args, **kwargs)

  

Django自定義裝飾器