Django自定义装饰器
装饰器模板:
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)