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
  • 相关阅读:
    javascript弹出窗口代码
    DOM的核心: Node
    AjaxControlToolkit学习系列(1) DragPanelExtender
    nodeName、nodeValue 以及 nodeType 简单解析
    AjaxControlToolkit学习系列(3) AnimationExtender
    childNodes
    javascript面向对象技术基础(四)
    自定义控件实现无刷新上传图片,立即显示缩略图,保存图片缩略图<原创>
    ADO.NET朝花夕拾(一)
    javascript面向对象技术基础(三)
  • 原文地址:https://www.cnblogs.com/wjun0/p/11559891.html
Copyright © 2011-2022 走看看