Request object and Response object of DRF

Posted by emceej on Thu, 16 Dec 2021 12:02:35 +0100

Request object and Response object of DRF

Once the DRF view is used, the Request object of the incoming view is not the Django Request object, but the DRF encapsulated Request object. Similarly, DRF recommends using the encapsulated Response to return the HTTP Response. When using this class to construct the Response object, the specific data content of the Response will be converted (render ed) to a type that meets the requirements of the front end.

Request object

The Request class of the REST framework extends the standard HttpRequest and adds support for the REST framework's flexible Request parsing and Request authentication. For implementation reasons, the Request class does not inherit from the HttpRequest class, but uses composition to extend the class. Therefore, the methods and properties of the HttpRequest class are still available.

Request.data

The data of the Request object is automatically parsed according to the format of the data sent by the front end. In this way, the back end uses a unified way to obtain data, whether the front end transmits forms, json or other formats. The back end can accept data in a unified way.

@api_view(['POST'])
def post(request):
    data = request.data     # Get request body data
    return Response(data)

It contains the data parsed by POST, PUT and PATCH request modes; parsers parser using REST framework supports not only form type data, but also JSON data.

If you need to upload files, please read DRF upload file

be careful

When developing client applications, always remember to ensure that Content-Type stay HTTP Sets the header when sending data in a request.

If you do not set the content type, most clients will use it by default'application/x-www-form-urlencoded',This may not be what you want.

For example, if you json Use with.ajax() Methodical jQuery If sending encoded data, ensure that it is included contentType: 'application/json'set up.

If the server and client have agreed to use json to transfer information, you can set the default parser at settings Add the following content to py.

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
    ]
}

You can also set up a parser for a single view or set of views using views based on the APIView class. For example:

# View set
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})

# Single view
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})

Request.query_params

request.query_params and Django standard request Get is the same, but with a more correct name. No matter what the request method is, we always use request in DRF for the parameters in the URL query_ Params. For example:

@api_view(['GET'])
def geta(request):
    data = request.query_params
    print(data)

    return Response(data)

Our requests can be as follows:

http://127.0.0.1:8888/people?username=123&email=123@123.com

The returned results are as follows:

{
    "username": "123",
    "email": "123@123.com"
}

Response object

The Response of the REST Framework is inherited from the SimpleTemplateResponse class of Django. Using the Response class only provides a better interface for returning the Web API Response of content negotiation, which can be presented in a variety of formats. You can also choose Django's HttpResponse or streaming HttpResponse, both of which are OK. However, DRF officials still suggest that we inherit from APIView class or use @ API_ The function decorated with view returns the Response object.

If the Response object is used, it will be returned with a certain style by default. For example:

reference material: https://www.django-rest-framework.org/api-guide/requests/ https://www.django-rest-framework.org/api-guide/responses/