Django REST framework parser and renderer

Parser

The role of the parser

Parser is the role of the server receives the client pass over the data, the data is parsed into data they can handle. It is essentially a data request parsing body.

Before looking at the parser, we must first know Accept and ContentType request header.

Accept: is to tell each other what kind of data I can resolve, you can often indicate what kind of data I want.

ContentType: I'll give you is to tell each other what kind of data type.

Parser works ContentType request is to get to the front to determine what data type I, and then we use the appropriate back-end parser to parse the data.

Data analysis in Django

In view we can to get the front-end data request sent by request.POST, then Django framework is how to get the data in the request body of it? Let's take a look together:

First, request object is an instance of an object WSGIRequest class, then we look at the code below:

 

from rest_framework.parsers import JSONParser,FormParser,MultiPartParser,FileUploadParser

 

 

 

 

 

 # Reset_framawork default route

 

 

from django.contrib import admin
from django.urls import path,re_path
from app01 import views
from rest_framework import  routers
from django.conf.urls import url,include


routers = routers.DefaultRouter()
routers.register("authors", views.AuthorModelView)



urlpatterns = [
    re_path(r'^',include(routers.urls)),

    # re_path(r'^admin/', admin.site.urls),
    # re_path(r'^publishes/$', views.PublishView.as_view(),name="publish"), #  View:view(request)=====APIView:dispatch()
    # re_path(r'^publishes/(?P<pk>\d+)/$', views.PublishDetailView.as_view(),name="detailpublish"), #  View:view(request)=====APIView:dispatch()
    #
    # re_path(r'^books/$', views.BookView.as_view(),name="books"),
    # re_path(r'^books/(\d+)/$', views.BookDetailView.as_view(),name="detailbook"),
    #url(r'^books/(\d+)/$', View:view),     # view(request)

    # re_path(r'^authors/$', views.AuthorModelView.as_view({"get":"list","post":"create"}),name="author"),
    # re_path(r'^authors/(?P<pk>\d+)/$', views.AuthorModelView.as_view({"get":"retrieve","put":"update","delete":"destroy"}),name="detailauthor"),

    re_path(r'^login/$', views.LoginView.as_view(),name="login"),

]

 

 

 

 

 

 

 

At this point we recall in Django views can be taken by the data and request.FILES request.POST here because requested data parsing, and assigned to the request object.

We also find that a problem, Django parser does not support ContenType is application / json, that can not be resolved json data format

 

The DRF parser

We all know that to get data access requests submitted by request.data, then request.data data come from the DRF in it? We look at the source code:

 

 

 

 

 

 

如果没有配置解析器,DRF会使用默认的解析器:

 

 

 

 

我们可以在单个视图或者全局的settings.py中配置要使用的解析器。

from rest_framework.response import Response

单个视图配置

class BookViewSet(ModelViewSet):
    queryset = models.Book.objects.all()
    serializer_class = BookModelSerializer
    parser_classes = [JSONParser, ]

全局配置

 

 

 

 

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
    )
}

注意:当你的项目中只配置了 JSONParser 解析器时,你的项目现在就只能解析JSON格式的数据了,客户端如果使用浏览器提交,那么你将无法解析。

注意,在视图类中定义的配置项的优先级要高于全局配置中的配置项

渲染器(rander)

渲染器同解析器相反,它定义了框架按照content_type来返回不同的响应。

DRF提供的渲染器有很多,默认是

 'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),

我们也可以在视图中局部设置也可以在全局的settings.py中进行设置:

局部设置

 

 

class PublisherViewSet(ModelViewSet):
    queryset = models.Publisher.objects.all()
    serializer_class = PublisherModelSerializer
    renderer_classes = [JSONRenderer, ]

这样设置后就只能返回JSON格式的数据了,并不会像之前一样提供一个阅读友好的web页面。

全局设置

 

 

 

 

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
}

注意,在视图类中定义的配置项的优先级要高于全局配置中的配置项。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/Rivend/p/11871719.html