- FBV和CBV其实就是要么写函数要么写类,那么内部原理是怎么实现?
FBV写法
def func_view(request):
"Function views"
if request.method == "GET":
return HttpResponse("GET-请求")
elif request.method == "POST":
return HttpResponse('POST-请求')
elif request.method == "PUT":
return HttpResponse('PUT-请求')
elif request.method == "DELETE":
return HttpResponse('DELETE-请求')
else:
return HttpResponse("不支持的请求类型")
CBV写法
class MyClassView(View):
def get(self, request, *args, **kwargs):
return HttpResponse("GET-请求")
def post(self, request, *args, **kwargs):
return HttpResponse("POST-请求")
def put(self, request, *args, **kwargs):
return HttpResponse("PUT-请求")
def delete(self, request, *args, **kwargs):
return HttpResponse("DELETE-请求")
原理
- FBV可以直接通过路由,调用到相应的视图函数,那么CBV呢?

微信截图_20190107211036
- 在我们的MyClassViewl里面没有as_view(),所以我们可以去父类找

微信截图_20190107211509
- 父类的as_view()方法

微信截图_20190107211710
- 在as_view()中也返回一个view

微信截图_20190107212833
- 分析as_view()当中的代码,调用了dispatch()方法

微信截图_20190107213123
- 在分析dispatch()方法前,我们先看看,当请求进来,通过URL先执行了as_view()函数,本质还是在执行内部的view()函数,而view()函数内部是执行了dispatch()方法

微信截图_20190107213809
- 不管什么请求进来,都执行dispatch()

微信截图_20190107213912
- 由于我们MyClassView里面没有dispatch()方法,所以会调用父类的dispatch(),如果我们有,那么会调用我们自己写的dispatch()方法

微信截图_20190107214135
- postman验证(http://127.0.0.1:8000/myclass_view/) 我们发现调用了我们自己写的dispatch()方法

微信截图_20190107214459
- 我们可以不看父类如何实现,我们可以自己尝试的写一下

微信截图_20190107214847
- 通过postman验证,发现也完成了这个相同的功能

微信截图_20190107215246
- 修正错误

微信截图_20190107215130
- postman验证效果

微信截图_20190107215339
- 观察父类的dispatch做什么?(其实本质就是基于反射实现)

微信截图_20190107215905
结论: CBV基于反射实现根据请求方式不同,执行不同方法
原理总结:
路由url -- > view函数 --> dispatch方法(根据反射来执行:GET/POST/PUT/DELETE等等....)