restframework parser, url control assembly

A parser

1 classification

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

a、JSONParser

Parse JSON data types

b、FormParser

Parsing the data type urlencode

c、MultiPartParser

Analytical data type form-data

d、FileUploadParser

Parse files uploaded

2, the default parser

DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
    ]

3, rewrite parser_classes

Add in the view class

parser_classes = [JSONParser]

Two, url control

1, causes

restframework view components, including the Senate resolved through as_view () get the two issues, to achieve the same kind of view, but there are still two url

2, solution

a, original

    path('author/', views.AuthorViewSet.as_view({'get': 'list', 'post': 'create'})),
    path('author/<pk>/', views.AuthorViewSet.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),

b, optimization

from rest_framework import routers
router = routers.DefaultRouter()
router.register('author', views.AuthorViewSet)

Secondary distribution

path('', include(router.urls)),

3, path

^author/$ [name='author-list']
^author\.(?P<format>[a-z0-9]+)/?$ [name='author-list']
^author/(?P<pk>[^/.]+)/$ [name='author-detail']
^author/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='author-detail']

supplement

a、?format=json

http://127.0.0.1:8000/author/?format=json

Role: to obtain data json format, no other decoration

b、.json

http://127.0.0.1:8000/author.json

Role: Get All json data

http://127.0.0.1:8000/author/6.json

Role: Gets the pk of json data

 

Guess you like

Origin www.cnblogs.com/wt7018/p/11470609.html