请求模块

请求模块

一 、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)
posted @ 2019-10-24 22:30  つつつつつつ  阅读(310)  评论(0编辑  收藏  举报