zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    自己写的一个读取execl的帮助类
    手动获取spring的ApplicationContext和bean对象
    前端开发不容错过的jQuery图片滑块插件(转)
    细说HTML元素的隐藏和显示
    DIV+CSS布局重新学习之使用A标签和CSS制作按钮
    opencv2函数学习之flip:实现图像翻转
    DWZ中Tree树形菜单的treeCheck如何获取返回值解决方案
    DWZ中刷新dialog的方案解决
    DWZ与KindEditor编辑器的整合
    ViewModel在MVC3中的应用:实现多字段表格的部分更新
  • 原文地址:https://www.cnblogs.com/wjun0/p/11559891.html
Copyright © 2011-2022 走看看