1. 程式人生 > >001---CBV和restful規範

001---CBV和restful規範

存在 http 做的 student `` roc failed for ESS

CBV 和 restful規範

知識點準備:

django的view

  • FBV:基於函數的視圖
  • CBV:基於類的視圖

    urls.py
    
    from django.urls import path
    from app01.views import StudentsView
    
    urlpatterns = [
    path('students/ ',StudentsView.as_view()),
    ]
    
    views.py
    
    from django.views import View
    from django.shortcuts import HttpResponse
    
    class StudentsView(View):
    
        def get(self,request,*args,**kwargs):
            return HttpResponse('GET 請求')
    
        def post(self,request,*args,**kwargs):
            return HttpResponse('POST 請求')

csrf_token

  • 原理:基於中間件的process__view()做的,用戶發送get請求的時候django會給他返回一個隨機字符串,下次用戶發送post請求的時候,要求攜帶這個隨機字符串,驗證是否一樣,
  • 免除:csrf_exempt
  • 驗證:csrf_protect
  • 為什麽不寫在process__request()裏面?
    因為它中間件要判斷視圖函數有沒有加免除或者驗證的裝飾器,如果在request裏面,他無法獲取哪些視圖函數加了裝飾器。
    # 第一種:給方法加
    from django.views import View
    from django.views.decorators.csrf import csrf_exempt, csrf_protect
    from django.utils.decorators import method_decorator
        
        
    class StudentsView(View):
    
        @method_decorator(csrf_exempt)
        def dispatch(self, request, *args, **kwargs):
            return super(StudentsView, self).dispatch(request, *args, **kwargs)
        
        def get(self, request, *args, **kwargs):
            
            print('GET')
            return HttpResponse('GET請求')
        
        def post(self, request, *args, **kwargs):
            return HttpResponse('POST請求')
             
    # 第二種:給類加
    @method_decorator(csrf_exempt,name='dispatch')
    class TeachersView(View):
    
        def get(self, request, *args, **kwargs):
            print('GET')
            return HttpResponse('GET請求')
        
        def post(self, request, *args, **kwargs):
            return HttpResponse('POST請求')
           

CBV源碼剖析

  • FBV 和 CBV
    基於反射實現根據請求方式不同,執行不同的方法
    原理:
    • 路由 cls.as_view()-->view()-->self.dispatch()-->反射
    • 視圖:get post delete put……
    • 流程
       class StudentsView(View):
    
           def dispatch(self, request, *args, **kwargs):
               # return HttpResponse('dispath')
               func = getattr(self,request.method.lower())
               return func(request, *args, **kwargs)
    
           def get(self, request, *args, **kwargs):
               return HttpResponse('GET請求')
    
           def post(self, request, *args, **kwargs):
               return HttpResponse('POST請求')
    
           def delete(self,request,*args,**kwargs):
               return HttpResponse('DELETE請求')
    
           def put(self,request,*args,**kwargs):
               return HttpResponse('PUT請求')
    • 繼承(多個類共用的功能,避免重復編寫)
       class MyBaseView(object):
           def dispatch(self, request, *args, **kwargs):
               print('before')
               func = super(MyBaseView, self).dispatch(request, *args, **kwargs)
               print('after')
               return func
    
    
       class StudentsView(MyBaseView, View):
    
           def get(self, request, *args, **kwargs):
               print('GET')
               return HttpResponse('GET請求')
    
           def post(self, request, *args, **kwargs):
               return HttpResponse('POST請求')
    
           def delete(self, request, *args, **kwargs):
               return HttpResponse('DELETE請求')
    
           def put(self, request, *args, **kwargs):
               return HttpResponse('PUT請求')

    restful規範

    十條規範

    • API與用戶的通信協議:https
    • 域名:
      • URL方式:www.abc.com/api/
      • 子域名方式(存在跨域問題) :www.abc.com www.api.abc.com
    • 版本:www.abc.com/api/v1/
    • 面向資源(視網絡上的任何數據為資源,均使用名詞、可復數):www.abc.com/api/v1/order/
    • 過濾,通過url傳遞搜索條件
    • 根據method不同進行不同的操作
      from django.urls import path
      from app01.views import OrderView
    
      urlpatterns = [
          path('order/',OrderView.as_view()),
      ]
    
      class OrderView(View):
    
          def get(self, request, *args, **kwargs):
              return HttpResponse('獲取訂單')
    
          def post(self, request, *args, **kwargs):
              return HttpResponse('創建訂單')
    
          def delete(self, request, *args, **kwargs):
              return HttpResponse('刪除訂單')
    
          def put(self, request, *args, **kwargs):
              return HttpResponse('更新訂單')
    
    • 狀態碼
    • 錯誤處理
    • 返回結果
    • 返回結果中就是url

django rest_framework

  • 安裝:pip install djangorestframework
  • 使用
    • 認證
      ```python
      from rest_framework.views import APIView
      from rest_framework.exceptions import AuthenticationFailed

        class MyAuthentication(object):
      
            def authenticate(self, request):
      
                token = request._request.GET.get('token')
                # 可以做用戶名密碼驗證
                if not token:
                    raise AuthenticationFailed('認證失敗')
                return (1, 2)
      
            def authenticate_header(self, request):
                pass
      
      
        class DogView(APIView):
            authentication_classes = [MyAuthentication]
      
            def get(self, request, *args, **kwargs):
                return HttpResponse('獲取小狗')
      
            def post(self, request, *args, **kwargs):
                return HttpResponse('創建小狗')
      
            def delete(self, request, *args, **kwargs):
                return HttpResponse('刪除小狗')
      
            def put(self, request, *args, **kwargs):
                return HttpResponse('更新小狗')

      ```

001---CBV和restful規範