• 给django视图类添加装饰器


    要将login_required装饰到view class的dispatch方法上,

    因为dispatch方法为类方法,不是单个的函数,所以需要将装饰函数的装饰器 login_required转化为装饰类方法的装饰器,就要用到method_decorator .

    method_decorator的参数可以是单个装饰器,也可是一个装饰器组成的列表

    from django.views.generic import View

    from django.contrib.auth.decorator import login_required

    from django.utils.decorators import method_decorator

    from django.contrib.auth.decorator import login_required,permission_required

    class MyView(View):

      @method_decorator(login_required)

      def dispatch(self,*args,**kwargs):

        return super(MyView,self).dispatch(*args,**kwargs)

      def get(self,request):

        pass

    将装饰器装饰到dispatch方法上,就相当于将装饰器装饰到该class的所有方法上,等效于:

    @method_decorator(permission_required('patient.session'),name="dispatch")

    class MyView(View):

      def get(self,request):

        pass

    如果只想应用于class中的某个方法中,可以直接装饰于该方法上

    class MyView(View):

      @method_decorator(login_required)

      def get(self,request):

        pass

    装饰器 :

    简单的装饰器形式为:

    def my_decorator(func):

      def _wrapped_view(*args,**kwargs):

          "do something "

          res=func(*args,**kwargs)

          "do other thing with the res "

          return "changed res"

      return _wrapped_view

    在方法内部定义一个函数,并将内部函数作为返回值

    这种方式是不改变被装饰的函数,但是返回一个具有额外属性的新函数来替换它,有时候我们想查看原函数的一些信息,比如 help(),name等信息

    这时,就返回装饰器内部定义函数的帮助信息和函数名,与我们原来的期待不一致。为了使被装饰后的函数,在查看函数自身的一些信息时,仍能获得

    期待的返回信息,需要使用functools.wraps

    对于带参数的装饰器只需在外部再嵌套一层函数:

    from functools import wraps 

    def for_some_use(some_params):  

      def my_decorator(func):

        @wraps(func)

        def _wrapped_view(*args,**kwargs):

          if some_params:

            print("not change the func")

            return func(*args,**kwargs)

          else:

            "do something "

            res=func(*args,**kwargs)

            "do other thing with the res "

            return "changed res"

        return _wrapped_view

    在一个方法上装饰多个装饰器,函数的定义是 最上面的装饰器在最外层,最靠近被装饰的函数的装饰器最先执行。

    对于这样的形式:

    @my_decorator1

    @my_decorator2

    @my_decorator3

    def my_func():

      pass

    相当于my_decorator1(my_decorator2(my_decorato3(my_func)))

  • 相关阅读:
    主流负载均衡器LVS、Nginx、HAProxy介绍
    shell脚本加密软件shc
    Linux系统安全配置相关
    Linux系统split对tar文件进行分片和压缩
    kubernetes组件详解和创建POD流程
    构建RPM之SPEC详解
    Python推荐系统框架:RecQ
    Python常用库-Psutil
    使用NLP从文章中自动提取关键字
    模糊字符串匹配:FuzzyWuzzy
  • 原文地址:https://www.cnblogs.com/Ting-light/p/10115584.html
Copyright © 2020-2023  润新知