drf(请求封装/认证/权限/节流)
Posted yzl2333
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了drf(请求封装/认证/权限/节流)相关的知识,希望对你有一定的参考价值。
1.请求的封装
class HttpRequest(object):
def __init__(self):
pass
@propery
def GET(self):
pass
@propery
def POST(self):
pass
@propery
def body(self):
pass
?
class Request(object):
def __init__(self,request):
self._request = request
def data(self):
if content-type == "application/json"
reutrn json.loads(self._request.body.decode(‘urf-8‘))
elif content-type == "x-www-...":
return self._request.POST
def query_params(self):
return self._reqeust.GET
?
req = HttpRequest()
request = Request(req)
?
request.data
request.query_prams
request._request.GET
request._request.POST
request._request.body
drf入口请求流程:
-
路由
urlpatterns = [
url(r‘^order/$‘, views.OrderView.as_view()),
] -
视图关系
class View(object):
2.版本
from django.conf.urls import url,include
from django.contrib import admin
from . import views
urlpatterns = [
url(r‘^order/$‘, views.OrderView.as_view()),
]
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
?
class OrderView(APIView):
def get(self,request,*args,**kwargs):
print(request.version)
print(request.versioning_scheme)
return Response(‘...‘)
?
def post(self,request,*args,**kwargs):
return Response(‘post‘)
源码流程:
?
?
class APIView(View):
versioning_class = api_settings.DEFAULT_VERSIONING_CLASS
def dispatch(self, request, *args, **kwargs):
# ###################### 第一步 ###########################
"""
request,是django的request,它的内部有:request.GET/request.POST/request.method
args,kwargs是在路由中匹配到的参数,如:
url(r‘^order/(d+)/(?P<version>w+)/$‘, views.OrderView.as_view()),
http://www.xxx.com/order/1/v2/
"""
self.args = args
self.kwargs = kwargs
?
"""
request = 生成了一个新的request对象,此对象的内部封装了一些值。
request = Request(request)
- 内部封装了 _request = 老的request
"""
request = self.initialize_request(request, *args, **kwargs)
self.request = request
?
self.headers = self.default_response_headers # deprecate?
?
try:
# ###################### 第二步 ###########################
self.initial(request, *args, **kwargs)
?
执行视图函数。。
def initial(self, request, *args, **kwargs):
# ############### 2.1 处理drf的版本 ##############
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
...
def determine_version(self, request, *args, **kwargs):
if self.versioning_class is None:
return (None,