Django自定义装饰器
Posted pythonclub
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
以上是关于Django自定义装饰器的主要内容,如果未能解决你的问题,请参考以下文章