1,步骤:
1,自定义装饰器
# 我们自定义的装饰器: def my_decorator_1(func): def wrapper(request, *args, **kwargs): print('自定义装饰器被调用了') print('请求路径%s' % request.path) return func(request, *args, **kwargs) return wrapper
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
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')
多个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')