使用多继承 以及类似java中的静态代理模式
原理:OrderView.as_view()根据广度优先,调用的是LoginRequiredMixin中的as_view(cls, *args, **kwargs)
这时的cls=OrderView
接下来super(LoginRequiredMixin, cls).as_view(*args, **kwargs) 会调用到View类中的as_view()并返回一个视图函数
然后,用将这个视图函数作为参数传给Login_required()并返回经过装饰的结果
class A(object): @classmethod def do(cls): print(‘我是你的眼‘) class B(object): @classmethod def do(cls): print(cls) super(B, cls).do() print("--" * 12) class C(B, A): pass if __name__ == ‘__main__‘: C.do() <class ‘__main__.C‘> 我是你的眼 ------------------------
from django.contrib.auth.decorators import login_required
class LoginRequiredMixin(object):
@classmethod
def as_view(cls, *args, **kwargs):
view = super(LoginRequiredMixin, cls).as_view(*args, **kwargs)
return login_required(view)
# /user/order
class OrderView(LoginRequiredMixin, View):
""" 用户中心 订单 """
def get(self, request):
context = {‘page‘: ‘order‘}
return render(request, ‘user/user_center_order.html‘, context)
urlpatterns = [
url(r‘^order/$‘, views.OrderView.as_view(), name=‘order‘),
]
原文地址:https://www.cnblogs.com/endurance9/p/10290057.html
时间: 2024-10-04 00:09:14