請求模塊

請求模塊

一 、CBV源碼分析

# 視圖層
from django.shortcuts import render, HttpResponse
from django.views import View

class CBVTest(View):
    # 經過調度(dispatch)分發請求
    def dispatch(self, request, *args, **kwargs):
        pass
        super().dispatch(request, *args, **kwargs)
        pass

    def get(self, request):
        return render(request, 'cbv.html')

    def post(self, request):
        return HttpResponse('cbv post method')
<!-- 模板層 -->
<form action="/cbv/" method="post">
    {% csrf_token %}
    <input type="text" name="usr">
    <button type="submit">提交</button>
</form>
# 路由層
from app import views
urlpatterns = [
    url(r'^cbv/', views.CBVTest.as_view()),
]

二 、DRF安裝與使用

2.1 安裝

  1. 安裝drfpip3 install djangorestframework
  2. settings.py註冊appINSTALLED_APPS = [..., 'rest_framework',]
  3. 基於cbv完成知足RSSTful規範的接口

2.2 使用

# 視圖層
from rest_framework.views import APIView
from rest_framework.response import Response
user_list = [{'id': 1, 'name': 'Bob'}, {'id': 2, 'name': 'Tom'}]
class Users(APIView):
    def get(self, request, *args, **kwargs):
        return Response({
            'status': 0,
            'msg': 'ok',
            'results': user_list
        })
    def post(self, request, *args, **kwargs):
        # request對formdata,urlencoded,json三個格式參數均能解析
        name = request.data.get('name')
        id = len(user_list) + 1
        user = {'id': id, 'name': name}
        user_list.append(user)
        return Response({
            'status': '0',
            'msg': 'ok',
            'results': user
        })
    
# 路由層
from app import views
urlpatterns = [
    url(r'^users/', views.Users.as_view()),
]

三 、request源碼分析

# as_view()
    # 核心走了父類as_view
    view = super(APIView, cls).as_view(**initkwargs)
    # 返回的是局部禁用csrf認證的view視圖函數
    return csrf_exempt(view)
    
# dispatch(self, request, *args, **kwargs)
    # 二次封裝request對象
    request = self.initialize_request(request, *args, **kwargs)
    # 自定義request規則
    self.initial(request, *args, **kwargs)
    
# initialize_request(self, request, *args, **kwargs)
    # 原生request封裝在request._request
    
# initial(self, request, *args, **kwargs)
    # 認證
    self.perform_authentication(request)
    # 權限
    self.check_permissions(request)
    # 頻率
    self.check_throttles(request)
相關文章
相關標籤/搜索