drf request and response
1. Request
The request object of the incoming view of the REST framework is no longer the default HttpRequest object of Django, but the object of the request class that extends the HttpRequest class provided by the REST framework.
The REST framework provides a Parser. After receiving the Request, it will automatically parse the Request data according to the Request data type specified by the content type (such as JSON, form, etc.), parse it into a class DICTIONARY [QueryDict] object and save it in the Request object.
# Core source code def __init__(self, request, parsers=None, authenticators=None, negotiator=None, parser_context=None): # Encapsulate the request twice, and take the native request as the name of the drf request object_ Request attribute self._request = request def __getattr__(self,item): return getattr(self._request,item)
The data of the Request object is automatically parsed according to the format of the data sent by the front end.
No matter what format of data is sent by the front end, we can read the data in a unified way.
1.1 common attributes
1).data
request.data returns the parsed request body data. Similar to the standard request in Django Post and request Files property, but provides the following features:
- Contains the parsed file and non file data
- It contains the data after parsing the POST, PUT and PATCH request modes
- parsers parser using REST framework supports not only form type data, but also JSON data
2).query_params
request.query_params and Django standard request Get is the same, but with a more correct name.
2. Response
from rest_framework.response import Response
The REST framework provides a Response class Response. When using this class to construct a Response object, the specific data content of the Response will be converted (render ed) into a type that meets the requirements of the front end.
The REST framework provides a Renderer to automatically convert the response data to the corresponding format according to the Accept (received data type declaration) in the request header. If there is no Accept declaration in the front-end request, the response data will be processed in the default way. We can modify the default response format through configuration.
Can be in rest_framework.settings to find all drf default configuration items
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( # Default response rendering class 'rest_framework.renderers.JSONRenderer', # json renderer 'rest_framework.renderers.BrowsableAPIRenderer', # Browse API renderer ) }
Local configuration: valid for a view class
-Write the following in the view class from rest_framework.renderers import JSONRenderer class Testview(APIView): renderer_classes=[JSONRenderer,] # Write it in the view class ...
2.1 construction mode
Response(data, status=None, template_name=None, headers=None, content_type=None)
The data data should not be the data processed by render, just pass the built-in type data of python, and the REST framework will use the renderer to process the data.
Data cannot be data with complex structure, such as Django's model class object. For such data, we can serialize it with Serializer serializer (convert it to Python dictionary type) and then pass it to the data parameter.
Parameter Description:
- Data: serialized data prepared for response;
- Status: status code, 200 by default;
- template_name: the name of the template. If HTMLRenderer is used, it should be indicated;
- headers: a dictionary used to store response header information;
- content_type: the content type of the response data. Generally, this parameter does not need to be passed. The REST framework will set this parameter according to the type data required by the front end.
2.2 common attributes
1).data
The serialized data passed to the response object but not yet processed by render
2).status_code
Number of status code
3).content
Response data after render processing
2.3 status code
For the convenience of setting the status code, REST framewrok is in rest_ framework. Common status code constants are provided in the status module.
1) Information notification - 1xx
HTTP_100_CONTINUE HTTP_101_SWITCHING_PROTOCOLS
2) Success - 2xx
HTTP_200_OK HTTP_201_CREATED HTTP_202_ACCEPTED HTTP_203_NON_AUTHORITATIVE_INFORMATION HTTP_204_NO_CONTENT HTTP_205_RESET_CONTENT HTTP_206_PARTIAL_CONTENT HTTP_207_MULTI_STATUS
3) Redirect - 3xx
HTTP_300_MULTIPLE_CHOICES HTTP_301_MOVED_PERMANENTLY HTTP_302_FOUND HTTP_303_SEE_OTHER HTTP_304_NOT_MODIFIED HTTP_305_USE_PROXY HTTP_306_RESERVED HTTP_307_TEMPORARY_REDIRECT
4) Client error - 4xx
HTTP_400_BAD_REQUEST HTTP_401_UNAUTHORIZED HTTP_402_PAYMENT_REQUIRED HTTP_403_FORBIDDEN HTTP_404_NOT_FOUND HTTP_405_METHOD_NOT_ALLOWED HTTP_406_NOT_ACCEPTABLE HTTP_407_PROXY_AUTHENTICATION_REQUIRED HTTP_408_REQUEST_TIMEOUT HTTP_409_CONFLICT HTTP_410_GONE HTTP_411_LENGTH_REQUIRED HTTP_412_PRECONDITION_FAILED HTTP_413_REQUEST_ENTITY_TOO_LARGE HTTP_414_REQUEST_URI_TOO_LONG HTTP_415_UNSUPPORTED_MEDIA_TYPE HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE HTTP_417_EXPECTATION_FAILED HTTP_422_UNPROCESSABLE_ENTITY HTTP_423_LOCKED HTTP_424_FAILED_DEPENDENCY HTTP_428_PRECONDITION_REQUIRED HTTP_429_TOO_MANY_REQUESTS HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS
5) Server error - 5xx
HTTP_500_INTERNAL_SERVER_ERROR HTTP_501_NOT_IMPLEMENTED HTTP_502_BAD_GATEWAY HTTP_503_SERVICE_UNAVAILABLE HTTP_504_GATEWAY_TIMEOUT HTTP_505_HTTP_VERSION_NOT_SUPPORTED HTTP_507_INSUFFICIENT_STORAGE HTTP_511_NETWORK_AUTHENTICATION_REQUIRED