views:
from django.views import Viewclass MyLogin(View):def get(self,request):return HttpResponse('get方法')def post(self,request):return HttpResponse('post方法')
urls:
path('MyLogin',views.MyLogin.as_view()),
CBV源码分析:
as_view()为入口
path('MyLogin',views.MyLogin.as_view()),
启动Django时候会立刻执行as_view方法,根据源码分析
就相当 path('MyLogin',viewsview),
def as_view(cls, **initkwargs):...def view(request, *args, **kwargs):...return view
本质在执行self.dispatch(request, *args, **kwargs)
去类(MyLogin类中找,找不到,去父类View)中找dispatch
def dispatch(self, request, *args, **kwargs):if request.method.lower() in self.http_method_names:handler = getattr(self, request.method.lower(), self.http_method_not_allowed)#反射:通过字符串来操作对象的属性或者方法#handler = getattr(自己写的类产生的对象,'get',当找不到get属性或者方法的时候就会用第三个参数)else:handler = self.http_method_not_allowedreturn handler(request, *args, **kwargs)