drf的安裝與設計風格

drf安裝與使用

restframework官網django

安裝drf:

pip3 install djangorestframeworkjson

drf的配置分析

# 1)安裝drf:pip3 install djangorestframework
# 2)settings.py註冊app:INSTALLED_APPS = [..., 'rest_framework']
# 3)基於cbv完成知足RSSTful規範的接口
# 視圖層
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()),
]

drf的封裝風格

  1. 設計風格,某一個功能就在工具包下面,全部的模塊都在功能名字內
from rest_framework.views import APIView  # 視圖
from rest_framework.request import Request  # 請求
from rest_framework.response import Response  # 響應
from rest_framework.filters import SearchFilter  # 過濾器
from rest_framework.pagination import PageNumberPagination  # 分頁
from rest_framework.exceptions import APIException  # 異常
from rest_framework.authentication import BaseAuthentication  # 認證
from rest_framework.permissions import IsAuthenticated  # 校驗認證
from rest_framework.throttling import SimpleRateThrottle  # 頻率認證
from rest_framework.settings import APISettings  # 設置
from rest_framework import status  # 狀態碼  點進去以後名字是對狀態碼的描述

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)
相關文章
相關標籤/搜索