Mixin 扩展类的使用
例如:
我们自定义的装饰器:
def my_decorator_1(func):
def wrapper(request, *args, **kwargs):
print(‘自定义装饰器被调用了’)
print(‘请求路径%s’ % request.path)
return func(request, *args, **kwargs)
return wrapper
定义的 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
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')
多个 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')
定义的扩展父类名称通常以 Mixin 结尾