1. 程式人生 > 實用技巧 >restful規範 之 CBV 實現介面流程梳理

restful規範 之 CBV 實現介面流程梳理

一、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) 

歡迎大家一起來討論學習!!!