• mixin 扩展类的装饰


    1,步骤:

      1,自定义装饰器  

    # 我们自定义的装饰器:
    def my_decorator_1(func):
        def wrapper(request, *args, **kwargs):
            print('自定义装饰器被调用了')
            print('请求路径%s' % request.path)
            return func(request, *args, **kwargs)
        return wrapper
    View Code

      

      2,定义Mixin扩展类(该类一定要继承object类,一定要重写as_view()函数)

    # 定义的 Mixin 扩展类:
    class FirstMixin(object):
        @classmethod
        def as_view(cls, *args, **kwargs):
            view = super().as_view(*args, **kwargs)
            view = my_decorator_1(view)
            return view
    View Code

      

      3,定义类视图,继承自:扩展类 + View (该类视图就是要装饰的视图,View一定要放在最后)

      (可以参考类继承顺序的调用,理解super().as_view的调用)

    # 定义的类视图, 继承自: 扩展类 + View
    class DemoView(FirstMixin, View):
        def get(self, request):
            print('demoview get')
            return HttpResponse('demoview get')
    
        def post(self, request):
            print('demoview post')
            return HttpResponse('demoview post')
    View Code

    多个Mixin扩展类的连用

    # 我们自定义的装饰器:
    def my_decorator_1(func):
        def wrapper(request, *args, **kwargs):
            print('自定义装饰器被调用了')
            print('请求路径%s' % request.path)
            return func(request, *args, **kwargs)
        return wrapper
    
    # 我们自定义的装饰器:
    def my_decorator_2(func):
        def wrapper(request, *args, **kwargs):
            print('自定义装饰器被调用了')
            print('请求路径%s' % request.path)
            return func(request, *args, **kwargs)
        return wrapper
    
    class FirstMixin(object):
        """ FirstMixin 扩展类 """
        @classmethod
        def as_view(cls, *args, **kwargs):
            view = super().as_view(*args, **kwargs)
            view = my_decorator_1(view)
            return view
    
    class SecondMixin(object):
        """ SecondMixin 扩展类 """ 
         @classmethod
        def as_view(cls, *args, **kwargs):
            view = super().as_view(*args, **kwargs)
            view = my_decorator_2(view)
            return view
    
    class DemoView(FirstMixin, SecondMixin, View):
        def get(self, request):
            print('demoview get')
            return HttpResponse('demoview get')
    
        def post(self, request):
            print('demoview post')
            return HttpResponse('demoview post')
    View Code
  • 相关阅读:
    Linux命令汇总(二)
    关于pyspark
    关于CDH
    hive通过spark导入hbase
    CentOS7的网络配置
    TTY,Console以及Terminal
    docker的操作
    docker安装与操作
    Wmware Player中Linux挂载U盘
    Mesos和Marathon
  • 原文地址:https://www.cnblogs.com/wjun0/p/11559891.html
Copyright © 2020-2023  润新知