一、CBV实现demo代码展示
1、urls.py
urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^Students/$',views.StudentView.as_view()), ]
2、views.py
from django.shortcuts import render,HttpResponse from django.views import View class StudentView(View): def get(self,request): print("查看所有的学生。。。") return HttpResponse("查看所有的学生。。。") def post(self,request): print("添加一个学生。。。") return HttpResponse("添加一个学生。。。")
3、通过postman请求接口 http://127.0.0.1:8000/Students/
二、CBV执行过程理解
备注:
在 StudentView(View)类的父类View下的dispatch方法理解:
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed) # getattr(object,name,default) object: 对象;name:字符串,对象属性;default:默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
欢迎大家一起来讨论学习!!!