Django http
When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument (request
of index
function below) to the view function. Each view is responsible for returning an HttpResponse object.
# in views.py
from djangp.http import HttpResponse
def index(request):
return HttpResponse('Test')
HttpRequest
(link to API doc)
There a number of attributes and methods; refer to the API doc.
HttpResponse
(link to API doc)
In contrast to HttpRequest
objects, which are created automatically by Django, HttpResponse
objects are your responsibility. Each view you write is responsible for instantiating, populating, and returning an HttpResponse
.
There a number of attributes and methods; refer to the API doc.
JsonResponse
(link to API doc)
class JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
An HttpResponse
subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with a couple differences:
Its default Content-Type
header is set to application/json
.
The first parameter, data, should be a dict instance. If the safe parameter is set to False
(see below) it can be any JSON-serializable object.
The encoder, which defaults to django.core.serializers.json.DjangoJSONEncoder
, will be used to serialize the data. See JSON serialization for more details about this serializer.
The safe boolean parameter defaults to True
. If it’s set to False
, any object can be passed for serialization (otherwise only dict instances are allowed). If safe is True and a non-dict object is passed as the first argument, a TypeError
will be raised.
The json_dumps_params parameter is a dictionary of keyword arguments to pass to the json.dumps()
call used to generate the response.