1. HttpResponse
After the Django server receives the request sent by the client, it will encapsulate the submitted data into an HttpRequest object and pass it to the view function. Then the view function also needs to return a response to the browser after processing the related logic. And for this response, we must return an object of HttpResponseBase or its subclasses. HttpResponse is the most used subclass of HttpResponseBase. Then let’s introduce HttpResponse and its subclasses.
1.1 Common attributes
- content: The content returned.
- status_code: The returned HTTP response status code.
- content_type: The MIME type of the returned data, the default is text/html. The browser will display the data based on this attribute. If it is text/html, then the string will be parsed, if text/plain, then a plain text will be displayed. The commonly used Content-Types are as follows:
- text/html (default, html file)
- text/plain (plain text)
- text/css (css file)
- text/javascript (js file)
- multipart/form-data (file submission)
- application/json (json transmission)
- application/xml (xml file)
- Set the request header: response[‘X-Access-Token’] =’xxxx’.
1.2 Common method
- set_cookie: used to set cookie information.
- delete_cookie: Used to delete cookie information.
- write: HttpResponse is an object similar to a file, which can be used to write data to the content.
2. JsonResponse
Used to dump the object into a json string, and then return to encapsulate the json string into a Response object and return it to the browser. And his Content-Type is application/json. The sample code is as follows.
from django.http import JsonResponse
def index(request):
return JsonResponse({"username":"jkc","age":18})
By default, JsonResponse can only dump dictionaries. If you want to dump non-dictionary data, you need to pass a safe=False parameter to JsonResponse. The sample code is as follows.
def index(request):
list1 = [
{"username": "jkc", "age": 18},
{"username": "a", "age": 20},
{"username": "b", "age": 22},
]
return JsonResponse(list1, safe=False)
In the above code, we define a list. When we want to dump data in non-dictionary format, we need to add the parameter safe=False.
2.1 JsonResponse class source code analysis
class JsonResponse(HttpResponse):
"""
An HTTP response class that consumes data to be serialized to JSON.
:param data: Data to be dumped into json. By default only ``dict`` objects
are allowed to be passed due to a security flaw before EcmaScript 5. See
the ``safe`` parameter for more information.
:param encoder: Should be a json encoder class. Defaults to
``django.core.serializers.json.DjangoJSONEncoder``.
:param safe: Controls if only ``dict`` objects may be serialized. Defaults
to ``True``.
:param json_dumps_params: A dictionary of kwargs passed to json.dumps().
"""
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
json_dumps_params=None, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError(
'In order to allow non-dict objects to be serialized set the '
'safe parameter to False.'
)
if json_dumps_params is None:
json_dumps_params = {}
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder, **json_dumps_params)
super().__init__(content=data, **kwargs)
We can see that JsonResponse is inherited from HttpResponse and has written an initialization method with 5 parameters.
- data: data to be converted
- encoder: json encoder
- safe: Control whether only dict objects can be serialized, the default is True
- json_dumps_params: The dictionary is converted by json.dumps()
The translation of the intermediate code is: if safe is set to True and the data type of data is not dict, then a TypeError type error is thrown, if json_dumps_params is None, kwargs sets a default value content_type=’application/json’, which specifies the returned It is in json format, and finally the data in dictionary format is converted into json format.