请求组件

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安装与使用

# 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()),
]

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 @ 2020-06-23 21:30  末兰岩  阅读(69)  评论(0编辑  收藏  举报