Django rest framework(5)----決議器
決議器
(1)api/urls.py
# api/urls.py
from django.urls import path,re_path
from .views import UserView,PaserView
urlpatterns = [
re_path('(?P<version>[v1|v2]+)/users/', UserView.as_view(),name = 'api_user'),
path('paser/', PaserView.as_view(),), #決議
]
(2)views.py
from rest_framework.parsers import JSONParser,FormParser
class PaserView(APIView):
parser_classes = [JSONParser,FormParser,]
#JSONParser:表示只能決議content-type:application/json的頭
#FormParser:表示只能決議content-type:application/x-www-form-urlencoded的頭
def post(self,request,*args,**kwargs):
#獲取決議后的結果
print(request.data)
return HttpResponse('paser')
(3)通過postman發送Json資料

在后臺可以獲取發過來的Json資料

原始碼流程
(1)dispatch
def dispatch(self, request, *args, **kwargs):
"""
`.dispatch()` is pretty much the same as Django's regular dispatch,
but with extra hooks for startup, finalize, and exception handling.
"""
self.args = args
self.kwargs = kwargs
#對原始request進行加工,豐富了一些功能
#Request(
# request,
# parsers=self.get_parsers(),
# authenticators=self.get_authenticators(),
# negotiator=self.get_content_negotiator(),
# parser_context=parser_context
# )
#request(原始request,[BasicAuthentications物件,])
#獲取原生request,request._request
#獲取認證類的物件,request.authticators
#1.封裝request
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
#2.認證
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
response = handler(request, *args, **kwargs)
except Exception as exc:
response = self.handle_exception(exc)
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
(2)initialize_request
獲取所有決議器
def initialize_request(self, request, *args, **kwargs):
"""
Returns the initial request object.
"""
parser_context = self.get_parser_context(request)
return Request(
request,
parsers=self.get_parsers(), #獲取所有的決議器
authenticators=self.get_authenticators(), #[BasicAuthentication(),],把所有的認證類物件封裝到request里面了
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
(3)get_parsers
def get_parsers(self):
"""
Instantiates and returns the list of parsers that this view can use.
"""
return [parser() for parser in self.parser_classes]
(4)parser_classes

同樣我們可以在settings里面全域配置
#全域配置
REST_FRAMEWORK = {
#版本
"DEFAULT_VERSIONING_CLASS":"rest_framework.versioning.URLPathVersioning",
#決議器
"DEFAULT_PARSER_CLASSES":["rest_framework.parsers.JSONParser","rest_framework.parsers.FormParser"]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/115649.html
標籤:Python
上一篇:13.DRF-版本
下一篇:Python:字串
