Django REST Framework API Guide (1) : Requesting Django REST Framework API Guide (2) : Responding to Django REST Framework API Guide (3) : Views Django REST Framework API Guide (4) : Generic Views Django REST Framework API Guide (5) : View Sets Django REST Framework API Guide (6) : Routing Django REST Framework API Guide (7) : Parsing

Link to official text

The parser

The REST Framework contains a number of built-in parser classes that allow you to accept requests for various media types. Custom parsers are also supported, which gives you the flexibility to design the types of media your API accepts.

How do I determine which parser to use

The valid set of parsers for a view is always defined as a list of classes. When accessing Request.data, the REST framework checks the content-Type of the incoming request and determines which parser to use to parse the request Content.

Note: When developing client applications, be sure to set Content-Type when sending data in HTTP requests. If you don’t set content Type, most clients will default to ‘application/X-www-form-urlencoded ‘, which may not be what you want. For example, if you are sending JSON data using jQuery and.ajax() methods, be sure to include contentType:’application/json’ setting.

Setting up the parser

You can set the default global parser using DEFAULT_PARSER_CLASSES. For example, the following Settings will only allow requests with JSON content, not the default JSON or form data.

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

You can also set up a parser for a single view or set of views on a class-based view.

from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    """ A view that can accept POST requests with JSON content. """
    parser_classes = (JSONParser,)

    def post(self, request, format=None):
        return Response({'received data': request.data})
Copy the code

Or with the @API_view decorator.

from rest_framework.decorators import api_view
from rest_framework.decorators import parser_classes
from rest_framework.parsers import JSONParser

@api_view(['POST'])
@parser_classes((JSONParser,))
def example_view(request, format=None):
    """ A view that can accept POST requests with JSON content. """
    return Response({'received data': request.data})
Copy the code

API reference

JSONParser

Parse the JSON request content.

Media_type: application/json

FormParser

Parse HTML form content. Request. data is a QueryDict dictionary that contains all form parameters.

You usually need to use both FormParser and MultiPartParser to fully support HTML form data.

Media_type: application/x – WWW – form – urlencoded

MultiPartParser

Parse the content of the multipart HTML form for file uploads. Request. data is a QueryDict (which contains form parameters and files).

You usually need to use both FormParser and MultiPartParser to fully support HTML form data.

Media_type: application/form – the data

FileUploadParser

Parse the uploaded file content. Request. data is a QueryDict (just a ‘file’ key that holds a file).

If the view used with FileUploadParser is called with the filename URL keyword argument, this parameter will be used as the filename.

If called without the filename URL keyword argument, the client must set the filename in the content-disposition HTTP header. For example the Content – Disposition: attachment; Filename = upload. JPG.

. Media_type: * / *

Please note:

  • FileUploadParserFor local clients, files can be uploaded as raw data request. You should use this for Web-based uploads, or for local clients with segmented upload supportMultiPartParserThe parser.
  • Due to this parsermedia_typeMatches any Content Type, soFileUploadParserShould normally be the only parser set up on the API view.
  • FileUploadParserFollow Django standardsFILE_UPLOAD_HANDLERSSet up andrequest.upload_handlersProperties. See the Django documentation for more details.

Basic usage examples:

# views.py
class FileUploadView(views.APIView):
    parser_classes = (FileUploadParser,)

    def put(self, request, filename, format=None):
        file_obj = request.data['file']
        #...
        # do some stuff with uploaded file
        #...
        return Response(status=204)

# urls.py
urlpatterns = [
    #...
    url(r'^upload/(? P
      
       [^/]+)$'
      , FileUploadView.as_view())
]
Copy the code

Custom parsing

To implement a custom parser, you should inherit BaseParser, set the.media_type attribute, and implement the.parse(self,stream,media_type,parser_context) method.

This method should return the data that will be used to populate the Request. data property.

The arguments passed to.parse() are:

stream

A streaming object representing the body of the request.

media_type

Optional. If provided, this is the media type that was passed in for the requested content.

Depending on the content-Type: header of the request, it can be more specific than the media_type attribute of the renderer and may contain the media Type parameter. Such as “text/plain; Charset = utf-8 “.

parser_context

Optional. If provided, this parameter will be a dictionary containing any additional context that might be needed to parse the request content.

By default, this will include the following keys: View, Request, args, kwargs.

Take a chestnut

Here is an example plain text parser that populates the Request.data property with a string representing the body of the request.

class PlainTextParser(BaseParser):
    """ Plain text parser. """
    media_type = 'text/plain'

    def parse(self, stream, media_type=None, parser_context=None):
        """ Simply return a string representing the body of the request. """
        return stream.read()
Copy the code

Third-party packages

The following are the third-party packages available.

YAML

REST Framework YAML provides YAML parsing and rendering support. It was previously included directly in the REST Framework package and is now available as a third-party package.

Installation and configuration

Install using PIP.

$ pip install djangorestframework-yaml
Copy the code

Modify REST Framework Settings.

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework_yaml.parsers.YAMLParser',),'DEFAULT_RENDERER_CLASSES': (
        'rest_framework_yaml.renderers.YAMLRenderer',).}Copy the code

XML

REST Framework XML provides a simple informal XML format. It was previously included directly in the REST Framework package and is now available as a third-party package.

Installation and configuration

Install using PIP.

$ pip install djangorestframework-xml
Copy the code

Modify REST Framework Settings.

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework_xml.parsers.XMLParser',),'DEFAULT_RENDERER_CLASSES': (
        'rest_framework_xml.renderers.XMLRenderer',).}Copy the code

MessagePack

CamelCase JSON

Helpful hints

With the source reading effect is better oh