装饰器

使用method_decorators添加装饰器

为类视图中的所有方法添加装饰器


  def decorator1(func):
      def wrapper(*args, **kwargs):
          print('decorator1')
          return func(*args, **kwargs)
      return wrapper


  def decorator2(func):
      def wrapper(*args, **kwargs):
          print('decorator2')
          return func(*args, **kwargs)
      return wrapper


  class DemoResource(Resource):
      method_decorators = [decorator1, decorator2]

      def get(self):
          return {'msg': 'get view'}

      def post(self):
          return {'msg': 'post view'}
为类视图中不同的方法添加不同的装饰器
  class DemoResource(Resource):
      method_decorators = {
          'get': [decorator1, decorator2],
          'post': [decorator1]
      }

      # 使用了decorator1 decorator2两个装饰器
      def get(self):
          return {'msg': 'get view'}

      # 使用了decorator1 装饰器
      def post(self):
          return {'msg': 'post view'}

      # 未使用装饰器
      def put(self):
          return {'msg': 'put view'}

代码理解原理

class DemoResource(Resource):
    method_decorators = [decorator1, decorator2]

    # for dec in method_decorators:
    #      func = dec(fuc)
    #
    #   get = decorator1(get)
    #   get = decorator2(get)
    # @decorator2
    # @decorator1
    # def get
    #     def decorator1(func):

#         def wrapper(*args, **kwargs):
#             print('decorator1')
#             return func(*args, **kwargs)
#
#         return wrapper
#
#     def decorator2(func):
#         def wrapper(*args, **kwargs):
#             print('decorator2')
#             return func(*args, **kwargs)
#         return wrapper
#
# get->  decorator2(  decorator1(get)     )
#     ->  decorator2(   decorator1->wrapper    )
#     ->  decorator2-> wrapper
#
# get() = decorator2-> wrapper()
#                 decorator1->wrapper()
#                     get()
    

总结: 装饰器执行顺序是从后至前开始的