1. ============================
    
  2. Request and response objects
    
  3. ============================
    
  4. 
    
  5. .. module:: django.http
    
  6.    :synopsis: Classes dealing with HTTP requests and responses.
    
  7. 
    
  8. Quick overview
    
  9. ==============
    
  10. 
    
  11. Django uses request and response objects to pass state through the system.
    
  12. 
    
  13. When a page is requested, Django creates an :class:`HttpRequest` object that
    
  14. contains metadata about the request. Then Django loads the appropriate view,
    
  15. passing the :class:`HttpRequest` as the first argument to the view function.
    
  16. Each view is responsible for returning an :class:`HttpResponse` object.
    
  17. 
    
  18. This document explains the APIs for :class:`HttpRequest` and
    
  19. :class:`HttpResponse` objects, which are defined in the :mod:`django.http`
    
  20. module.
    
  21. 
    
  22. ``HttpRequest`` objects
    
  23. =======================
    
  24. 
    
  25. .. class:: HttpRequest
    
  26. 
    
  27. .. _httprequest-attributes:
    
  28. 
    
  29. Attributes
    
  30. ----------
    
  31. 
    
  32. All attributes should be considered read-only, unless stated otherwise.
    
  33. 
    
  34. .. attribute:: HttpRequest.scheme
    
  35. 
    
  36.     A string representing the scheme of the request (``http`` or ``https``
    
  37.     usually).
    
  38. 
    
  39. .. attribute:: HttpRequest.body
    
  40. 
    
  41.     The raw HTTP request body as a bytestring. This is useful for processing
    
  42.     data in different ways than conventional HTML forms: binary images,
    
  43.     XML payload etc. For processing conventional form data, use
    
  44.     :attr:`HttpRequest.POST`.
    
  45. 
    
  46.     You can also read from an ``HttpRequest`` using a file-like interface with
    
  47.     :meth:`HttpRequest.read` or :meth:`HttpRequest.readline`. Accessing
    
  48.     the ``body`` attribute *after* reading the request with either of these I/O
    
  49.     stream methods will produce a ``RawPostDataException``.
    
  50. 
    
  51. .. attribute:: HttpRequest.path
    
  52. 
    
  53.     A string representing the full path to the requested page, not including
    
  54.     the scheme, domain, or query string.
    
  55. 
    
  56.     Example: ``"/music/bands/the_beatles/"``
    
  57. 
    
  58. .. attribute:: HttpRequest.path_info
    
  59. 
    
  60.     Under some web server configurations, the portion of the URL after the
    
  61.     host name is split up into a script prefix portion and a path info
    
  62.     portion. The ``path_info`` attribute always contains the path info portion
    
  63.     of the path, no matter what web server is being used. Using this instead
    
  64.     of :attr:`~HttpRequest.path` can make your code easier to move between
    
  65.     test and deployment servers.
    
  66. 
    
  67.     For example, if the ``WSGIScriptAlias`` for your application is set to
    
  68.     ``"/minfo"``, then ``path`` might be ``"/minfo/music/bands/the_beatles/"``
    
  69.     and ``path_info`` would be ``"/music/bands/the_beatles/"``.
    
  70. 
    
  71. .. attribute:: HttpRequest.method
    
  72. 
    
  73.     A string representing the HTTP method used in the request. This is
    
  74.     guaranteed to be uppercase. For example::
    
  75. 
    
  76.         if request.method == 'GET':
    
  77.             do_something()
    
  78.         elif request.method == 'POST':
    
  79.             do_something_else()
    
  80. 
    
  81. .. attribute:: HttpRequest.encoding
    
  82. 
    
  83.     A string representing the current encoding used to decode form submission
    
  84.     data (or ``None``, which means the :setting:`DEFAULT_CHARSET` setting is
    
  85.     used). You can write to this attribute to change the encoding used when
    
  86.     accessing the form data. Any subsequent attribute accesses (such as reading
    
  87.     from :attr:`GET` or :attr:`POST`) will use the new ``encoding`` value.
    
  88.     Useful if you know the form data is not in the :setting:`DEFAULT_CHARSET`
    
  89.     encoding.
    
  90. 
    
  91. .. attribute:: HttpRequest.content_type
    
  92. 
    
  93.     A string representing the MIME type of the request, parsed from the
    
  94.     ``CONTENT_TYPE`` header.
    
  95. 
    
  96. .. attribute:: HttpRequest.content_params
    
  97. 
    
  98.     A dictionary of key/value parameters included in the ``CONTENT_TYPE``
    
  99.     header.
    
  100. 
    
  101. .. attribute:: HttpRequest.GET
    
  102. 
    
  103.     A dictionary-like object containing all given HTTP GET parameters. See the
    
  104.     :class:`QueryDict` documentation below.
    
  105. 
    
  106. .. attribute:: HttpRequest.POST
    
  107. 
    
  108.     A dictionary-like object containing all given HTTP POST parameters,
    
  109.     providing that the request contains form data. See the
    
  110.     :class:`QueryDict` documentation below. If you need to access raw or
    
  111.     non-form data posted in the request, access this through the
    
  112.     :attr:`HttpRequest.body` attribute instead.
    
  113. 
    
  114.     It's possible that a request can come in via POST with an empty ``POST``
    
  115.     dictionary -- if, say, a form is requested via the POST HTTP method but
    
  116.     does not include form data. Therefore, you shouldn't use ``if request.POST``
    
  117.     to check for use of the POST method; instead, use ``if request.method ==
    
  118.     "POST"`` (see :attr:`HttpRequest.method`).
    
  119. 
    
  120.     ``POST`` does *not* include file-upload information. See :attr:`FILES`.
    
  121. 
    
  122. .. attribute:: HttpRequest.COOKIES
    
  123. 
    
  124.     A dictionary containing all cookies. Keys and values are strings.
    
  125. 
    
  126. .. attribute:: HttpRequest.FILES
    
  127. 
    
  128.     A dictionary-like object containing all uploaded files. Each key in
    
  129.     ``FILES`` is the ``name`` from the ``<input type="file" name="">``. Each
    
  130.     value in ``FILES`` is an :class:`~django.core.files.uploadedfile.UploadedFile`.
    
  131. 
    
  132.     See :doc:`/topics/files` for more information.
    
  133. 
    
  134.     ``FILES`` will only contain data if the request method was POST and the
    
  135.     ``<form>`` that posted to the request had ``enctype="multipart/form-data"``.
    
  136.     Otherwise, ``FILES`` will be a blank dictionary-like object.
    
  137. 
    
  138. .. attribute:: HttpRequest.META
    
  139. 
    
  140.     A dictionary containing all available HTTP headers. Available headers
    
  141.     depend on the client and server, but here are some examples:
    
  142. 
    
  143.     * ``CONTENT_LENGTH`` -- The length of the request body (as a string).
    
  144.     * ``CONTENT_TYPE`` -- The MIME type of the request body.
    
  145.     * ``HTTP_ACCEPT`` -- Acceptable content types for the response.
    
  146.     * ``HTTP_ACCEPT_ENCODING`` -- Acceptable encodings for the response.
    
  147.     * ``HTTP_ACCEPT_LANGUAGE`` -- Acceptable languages for the response.
    
  148.     * ``HTTP_HOST`` -- The HTTP Host header sent by the client.
    
  149.     * ``HTTP_REFERER`` -- The referring page, if any.
    
  150.     * ``HTTP_USER_AGENT`` -- The client's user-agent string.
    
  151.     * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
    
  152.     * ``REMOTE_ADDR`` -- The IP address of the client.
    
  153.     * ``REMOTE_HOST`` -- The hostname of the client.
    
  154.     * ``REMOTE_USER`` -- The user authenticated by the web server, if any.
    
  155.     * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
    
  156.     * ``SERVER_NAME`` -- The hostname of the server.
    
  157.     * ``SERVER_PORT`` -- The port of the server (as a string).
    
  158. 
    
  159.     With the exception of ``CONTENT_LENGTH`` and ``CONTENT_TYPE``, as given
    
  160.     above, any HTTP headers in the request are converted to ``META`` keys by
    
  161.     converting all characters to uppercase, replacing any hyphens with
    
  162.     underscores and adding an ``HTTP_`` prefix to the name. So, for example, a
    
  163.     header called ``X-Bender`` would be mapped to the ``META`` key
    
  164.     ``HTTP_X_BENDER``.
    
  165. 
    
  166.     Note that :djadmin:`runserver` strips all headers with underscores in the
    
  167.     name, so you won't see them in ``META``. This prevents header-spoofing
    
  168.     based on ambiguity between underscores and dashes both being normalizing to
    
  169.     underscores in WSGI environment variables. It matches the behavior of
    
  170.     web servers like Nginx and Apache 2.4+.
    
  171. 
    
  172.     :attr:`HttpRequest.headers` is a simpler way to access all HTTP-prefixed
    
  173.     headers, plus ``CONTENT_LENGTH`` and ``CONTENT_TYPE``.
    
  174. 
    
  175. .. attribute:: HttpRequest.headers
    
  176. 
    
  177.     A case insensitive, dict-like object that provides access to all
    
  178.     HTTP-prefixed headers (plus ``Content-Length`` and ``Content-Type``) from
    
  179.     the request.
    
  180. 
    
  181.     The name of each header is stylized with title-casing (e.g. ``User-Agent``)
    
  182.     when it's displayed. You can access headers case-insensitively::
    
  183. 
    
  184.         >>> request.headers
    
  185.         {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}
    
  186. 
    
  187.         >>> 'User-Agent' in request.headers
    
  188.         True
    
  189.         >>> 'user-agent' in request.headers
    
  190.         True
    
  191. 
    
  192.         >>> request.headers['User-Agent']
    
  193.         Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
    
  194.         >>> request.headers['user-agent']
    
  195.         Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
    
  196. 
    
  197.         >>> request.headers.get('User-Agent')
    
  198.         Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
    
  199.         >>> request.headers.get('user-agent')
    
  200.         Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
    
  201. 
    
  202.     For use in, for example, Django templates, headers can also be looked up
    
  203.     using underscores in place of hyphens::
    
  204. 
    
  205.         {{ request.headers.user_agent }}
    
  206. 
    
  207. .. attribute:: HttpRequest.resolver_match
    
  208. 
    
  209.     An instance of :class:`~django.urls.ResolverMatch` representing the
    
  210.     resolved URL. This attribute is only set after URL resolving took place,
    
  211.     which means it's available in all views but not in middleware which are
    
  212.     executed before URL resolving takes place (you can use it in
    
  213.     :meth:`process_view` though).
    
  214. 
    
  215. Attributes set by application code
    
  216. ----------------------------------
    
  217. 
    
  218. Django doesn't set these attributes itself but makes use of them if set by your
    
  219. application.
    
  220. 
    
  221. .. attribute:: HttpRequest.current_app
    
  222. 
    
  223.     The :ttag:`url` template tag will use its value as the ``current_app``
    
  224.     argument to :func:`~django.urls.reverse()`.
    
  225. 
    
  226. .. attribute:: HttpRequest.urlconf
    
  227. 
    
  228.     This will be used as the root URLconf for the current request, overriding
    
  229.     the :setting:`ROOT_URLCONF` setting. See
    
  230.     :ref:`how-django-processes-a-request` for details.
    
  231. 
    
  232.     ``urlconf`` can be set to ``None`` to revert any changes made by previous
    
  233.     middleware and return to using the :setting:`ROOT_URLCONF`.
    
  234. 
    
  235. .. attribute:: HttpRequest.exception_reporter_filter
    
  236. 
    
  237.     This will be used instead of :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER`
    
  238.     for the current request. See :ref:`custom-error-reports` for details.
    
  239. 
    
  240. .. attribute:: HttpRequest.exception_reporter_class
    
  241. 
    
  242.     This will be used instead of :setting:`DEFAULT_EXCEPTION_REPORTER` for the
    
  243.     current request. See :ref:`custom-error-reports` for details.
    
  244. 
    
  245. Attributes set by middleware
    
  246. ----------------------------
    
  247. 
    
  248. Some of the middleware included in Django's contrib apps set attributes on the
    
  249. request. If you don't see the attribute on a request, be sure the appropriate
    
  250. middleware class is listed in :setting:`MIDDLEWARE`.
    
  251. 
    
  252. .. attribute:: HttpRequest.session
    
  253. 
    
  254.     From the :class:`~django.contrib.sessions.middleware.SessionMiddleware`: A
    
  255.     readable and writable, dictionary-like object that represents the current
    
  256.     session.
    
  257. 
    
  258. .. attribute:: HttpRequest.site
    
  259. 
    
  260.     From the :class:`~django.contrib.sites.middleware.CurrentSiteMiddleware`:
    
  261.     An instance of :class:`~django.contrib.sites.models.Site` or
    
  262.     :class:`~django.contrib.sites.requests.RequestSite` as returned by
    
  263.     :func:`~django.contrib.sites.shortcuts.get_current_site()`
    
  264.     representing the current site.
    
  265. 
    
  266. .. attribute:: HttpRequest.user
    
  267. 
    
  268.     From the :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`:
    
  269.     An instance of :setting:`AUTH_USER_MODEL` representing the currently
    
  270.     logged-in user. If the user isn't currently logged in, ``user`` will be set
    
  271.     to an instance of :class:`~django.contrib.auth.models.AnonymousUser`. You
    
  272.     can tell them apart with
    
  273.     :attr:`~django.contrib.auth.models.User.is_authenticated`, like so::
    
  274. 
    
  275.         if request.user.is_authenticated:
    
  276.             ... # Do something for logged-in users.
    
  277.         else:
    
  278.             ... # Do something for anonymous users.
    
  279. 
    
  280. Methods
    
  281. -------
    
  282. 
    
  283. .. method:: HttpRequest.get_host()
    
  284. 
    
  285.     Returns the originating host of the request using information from the
    
  286.     ``HTTP_X_FORWARDED_HOST`` (if :setting:`USE_X_FORWARDED_HOST` is enabled)
    
  287.     and ``HTTP_HOST`` headers, in that order. If they don't provide a value,
    
  288.     the method uses a combination of ``SERVER_NAME`` and ``SERVER_PORT`` as
    
  289.     detailed in :pep:`3333`.
    
  290. 
    
  291.     Example: ``"127.0.0.1:8000"``
    
  292. 
    
  293.     Raises ``django.core.exceptions.DisallowedHost`` if the host is not in
    
  294.     :setting:`ALLOWED_HOSTS` or the domain name is invalid according to
    
  295.     :rfc:`1034`/:rfc:`1035 <1035>`.
    
  296. 
    
  297.     .. note:: The :meth:`~HttpRequest.get_host()` method fails when the host is
    
  298.         behind multiple proxies. One solution is to use middleware to rewrite
    
  299.         the proxy headers, as in the following example::
    
  300. 
    
  301.             class MultipleProxyMiddleware:
    
  302.                 FORWARDED_FOR_FIELDS = [
    
  303.                     'HTTP_X_FORWARDED_FOR',
    
  304.                     'HTTP_X_FORWARDED_HOST',
    
  305.                     'HTTP_X_FORWARDED_SERVER',
    
  306.                 ]
    
  307. 
    
  308.                 def __init__(self, get_response):
    
  309.                     self.get_response = get_response
    
  310. 
    
  311.                 def __call__(self, request):
    
  312.                     """
    
  313.                     Rewrites the proxy headers so that only the most
    
  314.                     recent proxy is used.
    
  315.                     """
    
  316.                     for field in self.FORWARDED_FOR_FIELDS:
    
  317.                         if field in request.META:
    
  318.                             if ',' in request.META[field]:
    
  319.                                 parts = request.META[field].split(',')
    
  320.                                 request.META[field] = parts[-1].strip()
    
  321.                     return self.get_response(request)
    
  322. 
    
  323.         This middleware should be positioned before any other middleware that
    
  324.         relies on the value of :meth:`~HttpRequest.get_host()` -- for instance,
    
  325.         :class:`~django.middleware.common.CommonMiddleware` or
    
  326.         :class:`~django.middleware.csrf.CsrfViewMiddleware`.
    
  327. 
    
  328. .. method:: HttpRequest.get_port()
    
  329. 
    
  330.     Returns the originating port of the request using information from the
    
  331.     ``HTTP_X_FORWARDED_PORT`` (if :setting:`USE_X_FORWARDED_PORT` is enabled)
    
  332.     and ``SERVER_PORT`` ``META`` variables, in that order.
    
  333. 
    
  334. .. method:: HttpRequest.get_full_path()
    
  335. 
    
  336.     Returns the ``path``, plus an appended query string, if applicable.
    
  337. 
    
  338.     Example: ``"/music/bands/the_beatles/?print=true"``
    
  339. 
    
  340. .. method:: HttpRequest.get_full_path_info()
    
  341. 
    
  342.     Like :meth:`get_full_path`, but uses :attr:`path_info` instead of
    
  343.     :attr:`path`.
    
  344. 
    
  345.     Example: ``"/minfo/music/bands/the_beatles/?print=true"``
    
  346. 
    
  347. .. method:: HttpRequest.build_absolute_uri(location=None)
    
  348. 
    
  349.     Returns the absolute URI form of ``location``. If no location is provided,
    
  350.     the location will be set to ``request.get_full_path()``.
    
  351. 
    
  352.     If the location is already an absolute URI, it will not be altered.
    
  353.     Otherwise the absolute URI is built using the server variables available in
    
  354.     this request. For example:
    
  355. 
    
  356.     >>> request.build_absolute_uri()
    
  357.     'https://example.com/music/bands/the_beatles/?print=true'
    
  358.     >>> request.build_absolute_uri('/bands/')
    
  359.     'https://example.com/bands/'
    
  360.     >>> request.build_absolute_uri('https://example2.com/bands/')
    
  361.     'https://example2.com/bands/'
    
  362. 
    
  363.     .. note::
    
  364. 
    
  365.         Mixing HTTP and HTTPS on the same site is discouraged, therefore
    
  366.         :meth:`~HttpRequest.build_absolute_uri()` will always generate an
    
  367.         absolute URI with the same scheme the current request has. If you need
    
  368.         to redirect users to HTTPS, it's best to let your web server redirect
    
  369.         all HTTP traffic to HTTPS.
    
  370. 
    
  371. .. method:: HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
    
  372. 
    
  373.     Returns a cookie value for a signed cookie, or raises a
    
  374.     ``django.core.signing.BadSignature`` exception if the signature is
    
  375.     no longer valid. If you provide the ``default`` argument the exception
    
  376.     will be suppressed and that default value will be returned instead.
    
  377. 
    
  378.     The optional ``salt`` argument can be used to provide extra protection
    
  379.     against brute force attacks on your secret key. If supplied, the
    
  380.     ``max_age`` argument will be checked against the signed timestamp
    
  381.     attached to the cookie value to ensure the cookie is not older than
    
  382.     ``max_age`` seconds.
    
  383. 
    
  384.     For example::
    
  385. 
    
  386.         >>> request.get_signed_cookie('name')
    
  387.         'Tony'
    
  388.         >>> request.get_signed_cookie('name', salt='name-salt')
    
  389.         'Tony' # assuming cookie was set using the same salt
    
  390.         >>> request.get_signed_cookie('nonexistent-cookie')
    
  391.         ...
    
  392.         KeyError: 'nonexistent-cookie'
    
  393.         >>> request.get_signed_cookie('nonexistent-cookie', False)
    
  394.         False
    
  395.         >>> request.get_signed_cookie('cookie-that-was-tampered-with')
    
  396.         ...
    
  397.         BadSignature: ...
    
  398.         >>> request.get_signed_cookie('name', max_age=60)
    
  399.         ...
    
  400.         SignatureExpired: Signature age 1677.3839159 > 60 seconds
    
  401.         >>> request.get_signed_cookie('name', False, max_age=60)
    
  402.         False
    
  403. 
    
  404.     See :doc:`cryptographic signing </topics/signing>` for more information.
    
  405. 
    
  406. .. method:: HttpRequest.is_secure()
    
  407. 
    
  408.     Returns ``True`` if the request is secure; that is, if it was made with
    
  409.     HTTPS.
    
  410. 
    
  411. .. method:: HttpRequest.accepts(mime_type)
    
  412. 
    
  413.     Returns ``True`` if the request ``Accept`` header matches the ``mime_type``
    
  414.     argument::
    
  415. 
    
  416.         >>> request.accepts('text/html')
    
  417.         True
    
  418. 
    
  419.     Most browsers send ``Accept: */*`` by default, so this would return
    
  420.     ``True`` for all content types. Setting an explicit ``Accept`` header in
    
  421.     API requests can be useful for returning a different content type for those
    
  422.     consumers only. See :ref:`content-negotiation-example` of using
    
  423.     ``accepts()`` to return different content to API consumers.
    
  424. 
    
  425.     If a response varies depending on the content of the ``Accept`` header and
    
  426.     you are using some form of caching like Django's :mod:`cache middleware
    
  427.     <django.middleware.cache>`, you should decorate the view with
    
  428.     :func:`vary_on_headers('Accept')
    
  429.     <django.views.decorators.vary.vary_on_headers>` so that the responses are
    
  430.     properly cached.
    
  431. 
    
  432. .. method:: HttpRequest.read(size=None)
    
  433. .. method:: HttpRequest.readline()
    
  434. .. method:: HttpRequest.readlines()
    
  435. .. method:: HttpRequest.__iter__()
    
  436. 
    
  437.     Methods implementing a file-like interface for reading from an
    
  438.     ``HttpRequest`` instance. This makes it possible to consume an incoming
    
  439.     request in a streaming fashion. A common use-case would be to process a
    
  440.     big XML payload with an iterative parser without constructing a whole
    
  441.     XML tree in memory.
    
  442. 
    
  443.     Given this standard interface, an ``HttpRequest`` instance can be
    
  444.     passed directly to an XML parser such as
    
  445.     :class:`~xml.etree.ElementTree.ElementTree`::
    
  446. 
    
  447.         import xml.etree.ElementTree as ET
    
  448.         for element in ET.iterparse(request):
    
  449.             process(element)
    
  450. 
    
  451. 
    
  452. ``QueryDict`` objects
    
  453. =====================
    
  454. 
    
  455. .. class:: QueryDict
    
  456. 
    
  457. In an :class:`HttpRequest` object, the :attr:`~HttpRequest.GET` and
    
  458. :attr:`~HttpRequest.POST` attributes are instances of ``django.http.QueryDict``,
    
  459. a dictionary-like class customized to deal with multiple values for the same
    
  460. key. This is necessary because some HTML form elements, notably
    
  461. ``<select multiple>``, pass multiple values for the same key.
    
  462. 
    
  463. The ``QueryDict``\ s at ``request.POST`` and ``request.GET`` will be immutable
    
  464. when accessed in a normal request/response cycle. To get a mutable version you
    
  465. need to use :meth:`QueryDict.copy`.
    
  466. 
    
  467. Methods
    
  468. -------
    
  469. 
    
  470. :class:`QueryDict` implements all the standard dictionary methods because it's
    
  471. a subclass of dictionary. Exceptions are outlined here:
    
  472. 
    
  473. .. method:: QueryDict.__init__(query_string=None, mutable=False, encoding=None)
    
  474. 
    
  475.     Instantiates a ``QueryDict`` object based on ``query_string``.
    
  476. 
    
  477.     >>> QueryDict('a=1&a=2&c=3')
    
  478.     <QueryDict: {'a': ['1', '2'], 'c': ['3']}>
    
  479. 
    
  480.     If ``query_string`` is not passed in, the resulting ``QueryDict`` will be
    
  481.     empty (it will have no keys or values).
    
  482. 
    
  483.     Most ``QueryDict``\ s you encounter, and in particular those at
    
  484.     ``request.POST`` and ``request.GET``, will be immutable. If you are
    
  485.     instantiating one yourself, you can make it mutable by passing
    
  486.     ``mutable=True`` to its ``__init__()``.
    
  487. 
    
  488.     Strings for setting both keys and values will be converted from ``encoding``
    
  489.     to ``str``. If ``encoding`` is not set, it defaults to
    
  490.     :setting:`DEFAULT_CHARSET`.
    
  491. 
    
  492. .. classmethod:: QueryDict.fromkeys(iterable, value='', mutable=False, encoding=None)
    
  493. 
    
  494.     Creates a new ``QueryDict`` with keys from ``iterable`` and each value
    
  495.     equal to ``value``. For example::
    
  496. 
    
  497.         >>> QueryDict.fromkeys(['a', 'a', 'b'], value='val')
    
  498.         <QueryDict: {'a': ['val', 'val'], 'b': ['val']}>
    
  499. 
    
  500. .. method:: QueryDict.__getitem__(key)
    
  501. 
    
  502.     Returns the value for the given key. If the key has more than one value,
    
  503.     it returns the last value. Raises
    
  504.     ``django.utils.datastructures.MultiValueDictKeyError`` if the key does not
    
  505.     exist. (This is a subclass of Python's standard :exc:`KeyError`, so you can
    
  506.     stick to catching ``KeyError``.)
    
  507. 
    
  508. .. method:: QueryDict.__setitem__(key, value)
    
  509. 
    
  510.     Sets the given key to ``[value]`` (a list whose single element is
    
  511.     ``value``). Note that this, as other dictionary functions that have side
    
  512.     effects, can only be called on a mutable ``QueryDict`` (such as one that
    
  513.     was created via :meth:`QueryDict.copy`).
    
  514. 
    
  515. .. method:: QueryDict.__contains__(key)
    
  516. 
    
  517.     Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
    
  518.     in request.GET``.
    
  519. 
    
  520. .. method:: QueryDict.get(key, default=None)
    
  521. 
    
  522.     Uses the same logic as :meth:`__getitem__`, with a hook for returning a
    
  523.     default value if the key doesn't exist.
    
  524. 
    
  525. .. method:: QueryDict.setdefault(key, default=None)
    
  526. 
    
  527.     Like :meth:`dict.setdefault`, except it uses :meth:`__setitem__` internally.
    
  528. 
    
  529. .. method:: QueryDict.update(other_dict)
    
  530. 
    
  531.     Takes either a ``QueryDict`` or a dictionary. Like :meth:`dict.update`,
    
  532.     except it *appends* to the current dictionary items rather than replacing
    
  533.     them. For example::
    
  534. 
    
  535.         >>> q = QueryDict('a=1', mutable=True)
    
  536.         >>> q.update({'a': '2'})
    
  537.         >>> q.getlist('a')
    
  538.         ['1', '2']
    
  539.         >>> q['a'] # returns the last
    
  540.         '2'
    
  541. 
    
  542. .. method:: QueryDict.items()
    
  543. 
    
  544.     Like :meth:`dict.items`, except this uses the same last-value logic as
    
  545.     :meth:`__getitem__` and returns an iterator object instead of a view object.
    
  546.     For example::
    
  547. 
    
  548.         >>> q = QueryDict('a=1&a=2&a=3')
    
  549.         >>> list(q.items())
    
  550.         [('a', '3')]
    
  551. 
    
  552. .. method:: QueryDict.values()
    
  553. 
    
  554.     Like :meth:`dict.values`, except this uses the same last-value logic as
    
  555.     :meth:`__getitem__` and returns an iterator instead of a view object. For
    
  556.     example::
    
  557. 
    
  558.         >>> q = QueryDict('a=1&a=2&a=3')
    
  559.         >>> list(q.values())
    
  560.         ['3']
    
  561. 
    
  562. In addition, ``QueryDict`` has the following methods:
    
  563. 
    
  564. .. method:: QueryDict.copy()
    
  565. 
    
  566.     Returns a copy of the object using :func:`copy.deepcopy`. This copy will
    
  567.     be mutable even if the original was not.
    
  568. 
    
  569. .. method:: QueryDict.getlist(key, default=None)
    
  570. 
    
  571.     Returns a list of the data with the requested key. Returns an empty list if
    
  572.     the key doesn't exist and ``default`` is ``None``. It's guaranteed to
    
  573.     return a list unless the default value provided isn't a list.
    
  574. 
    
  575. .. method:: QueryDict.setlist(key, list_)
    
  576. 
    
  577.     Sets the given key to ``list_`` (unlike :meth:`__setitem__`).
    
  578. 
    
  579. .. method:: QueryDict.appendlist(key, item)
    
  580. 
    
  581.     Appends an item to the internal list associated with key.
    
  582. 
    
  583. .. method:: QueryDict.setlistdefault(key, default_list=None)
    
  584. 
    
  585.     Like :meth:`setdefault`, except it takes a list of values instead of a
    
  586.     single value.
    
  587. 
    
  588. .. method:: QueryDict.lists()
    
  589. 
    
  590.     Like :meth:`items()`, except it includes all values, as a list, for each
    
  591.     member of the dictionary. For example::
    
  592. 
    
  593.         >>> q = QueryDict('a=1&a=2&a=3')
    
  594.         >>> q.lists()
    
  595.         [('a', ['1', '2', '3'])]
    
  596. 
    
  597. .. method:: QueryDict.pop(key)
    
  598. 
    
  599.     Returns a list of values for the given key and removes them from the
    
  600.     dictionary. Raises ``KeyError`` if the key does not exist. For example::
    
  601. 
    
  602.         >>> q = QueryDict('a=1&a=2&a=3', mutable=True)
    
  603.         >>> q.pop('a')
    
  604.         ['1', '2', '3']
    
  605. 
    
  606. .. method:: QueryDict.popitem()
    
  607. 
    
  608.     Removes an arbitrary member of the dictionary (since there's no concept
    
  609.     of ordering), and returns a two value tuple containing the key and a list
    
  610.     of all values for the key. Raises ``KeyError`` when called on an empty
    
  611.     dictionary. For example::
    
  612. 
    
  613.         >>> q = QueryDict('a=1&a=2&a=3', mutable=True)
    
  614.         >>> q.popitem()
    
  615.         ('a', ['1', '2', '3'])
    
  616. 
    
  617. .. method:: QueryDict.dict()
    
  618. 
    
  619.     Returns a ``dict`` representation of ``QueryDict``. For every (key, list)
    
  620.     pair in ``QueryDict``, ``dict`` will have (key, item), where item is one
    
  621.     element of the list, using the same logic as :meth:`QueryDict.__getitem__`::
    
  622. 
    
  623.         >>> q = QueryDict('a=1&a=3&a=5')
    
  624.         >>> q.dict()
    
  625.         {'a': '5'}
    
  626. 
    
  627. .. method:: QueryDict.urlencode(safe=None)
    
  628. 
    
  629.     Returns a string of the data in query string format. For example::
    
  630. 
    
  631.         >>> q = QueryDict('a=2&b=3&b=5')
    
  632.         >>> q.urlencode()
    
  633.         'a=2&b=3&b=5'
    
  634. 
    
  635.     Use the ``safe`` parameter to pass characters which don't require encoding.
    
  636.     For example::
    
  637. 
    
  638.         >>> q = QueryDict(mutable=True)
    
  639.         >>> q['next'] = '/a&b/'
    
  640.         >>> q.urlencode(safe='/')
    
  641.         'next=/a%26b/'
    
  642. 
    
  643. ``HttpResponse`` objects
    
  644. ========================
    
  645. 
    
  646. .. class:: HttpResponse
    
  647. 
    
  648. In contrast to :class:`HttpRequest` objects, which are created automatically by
    
  649. Django, :class:`HttpResponse` objects are your responsibility. Each view you
    
  650. write is responsible for instantiating, populating, and returning an
    
  651. :class:`HttpResponse`.
    
  652. 
    
  653. The :class:`HttpResponse` class lives in the :mod:`django.http` module.
    
  654. 
    
  655. Usage
    
  656. -----
    
  657. 
    
  658. Passing strings
    
  659. ~~~~~~~~~~~~~~~
    
  660. 
    
  661. Typical usage is to pass the contents of the page, as a string, bytestring,
    
  662. or :class:`memoryview`, to the :class:`HttpResponse` constructor::
    
  663. 
    
  664.     >>> from django.http import HttpResponse
    
  665.     >>> response = HttpResponse("Here's the text of the web page.")
    
  666.     >>> response = HttpResponse("Text only, please.", content_type="text/plain")
    
  667.     >>> response = HttpResponse(b'Bytestrings are also accepted.')
    
  668.     >>> response = HttpResponse(memoryview(b'Memoryview as well.'))
    
  669. 
    
  670. But if you want to add content incrementally, you can use ``response`` as a
    
  671. file-like object::
    
  672. 
    
  673.     >>> response = HttpResponse()
    
  674.     >>> response.write("<p>Here's the text of the web page.</p>")
    
  675.     >>> response.write("<p>Here's another paragraph.</p>")
    
  676. 
    
  677. Passing iterators
    
  678. ~~~~~~~~~~~~~~~~~
    
  679. 
    
  680. Finally, you can pass ``HttpResponse`` an iterator rather than strings.
    
  681. ``HttpResponse`` will consume the iterator immediately, store its content as a
    
  682. string, and discard it. Objects with a ``close()`` method such as files and
    
  683. generators are immediately closed.
    
  684. 
    
  685. If you need the response to be streamed from the iterator to the client, you
    
  686. must use the :class:`StreamingHttpResponse` class instead.
    
  687. 
    
  688. .. _setting-header-fields:
    
  689. 
    
  690. Setting header fields
    
  691. ~~~~~~~~~~~~~~~~~~~~~
    
  692. 
    
  693. To set or remove a header field in your response, use
    
  694. :attr:`HttpResponse.headers`::
    
  695. 
    
  696.     >>> response = HttpResponse()
    
  697.     >>> response.headers['Age'] = 120
    
  698.     >>> del response.headers['Age']
    
  699. 
    
  700. You can also manipulate headers by treating your response like a dictionary::
    
  701. 
    
  702.     >>> response = HttpResponse()
    
  703.     >>> response['Age'] = 120
    
  704.     >>> del response['Age']
    
  705. 
    
  706. This proxies to ``HttpResponse.headers``, and is the original interface offered
    
  707. by ``HttpResponse``.
    
  708. 
    
  709. When using this interface, unlike a dictionary, ``del`` doesn't raise
    
  710. ``KeyError`` if the header field doesn't exist.
    
  711. 
    
  712. You can also set headers on instantiation::
    
  713. 
    
  714.     >>> response = HttpResponse(headers={'Age': 120})
    
  715. 
    
  716. For setting the ``Cache-Control`` and ``Vary`` header fields, it is recommended
    
  717. to use the :func:`~django.utils.cache.patch_cache_control` and
    
  718. :func:`~django.utils.cache.patch_vary_headers` methods from
    
  719. :mod:`django.utils.cache`, since these fields can have multiple, comma-separated
    
  720. values. The "patch" methods ensure that other values, e.g. added by a
    
  721. middleware, are not removed.
    
  722. 
    
  723. HTTP header fields cannot contain newlines. An attempt to set a header field
    
  724. containing a newline character (CR or LF) will raise ``BadHeaderError``
    
  725. 
    
  726. Telling the browser to treat the response as a file attachment
    
  727. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  728. 
    
  729. To tell the browser to treat the response as a file attachment, set the
    
  730. ``Content-Type`` and ``Content-Disposition`` headers. For example, this is how
    
  731. you might return a Microsoft Excel spreadsheet::
    
  732. 
    
  733.     >>> response = HttpResponse(my_data, headers={
    
  734.     ...     'Content-Type': 'application/vnd.ms-excel',
    
  735.     ...     'Content-Disposition': 'attachment; filename="foo.xls"',
    
  736.     ... })
    
  737. 
    
  738. There's nothing Django-specific about the ``Content-Disposition`` header, but
    
  739. it's easy to forget the syntax, so we've included it here.
    
  740. 
    
  741. Attributes
    
  742. ----------
    
  743. 
    
  744. .. attribute:: HttpResponse.content
    
  745. 
    
  746.     A bytestring representing the content, encoded from a string if necessary.
    
  747. 
    
  748. .. attribute:: HttpResponse.headers
    
  749. 
    
  750.     A case insensitive, dict-like object that provides an interface to all
    
  751.     HTTP headers on the response. See :ref:`setting-header-fields`.
    
  752. 
    
  753. .. attribute:: HttpResponse.charset
    
  754. 
    
  755.     A string denoting the charset in which the response will be encoded. If not
    
  756.     given at ``HttpResponse`` instantiation time, it will be extracted from
    
  757.     ``content_type`` and if that is unsuccessful, the
    
  758.     :setting:`DEFAULT_CHARSET` setting will be used.
    
  759. 
    
  760. .. attribute:: HttpResponse.status_code
    
  761. 
    
  762.     The :rfc:`HTTP status code <7231#section-6>` for the response.
    
  763. 
    
  764.     Unless :attr:`reason_phrase` is explicitly set, modifying the value of
    
  765.     ``status_code`` outside the constructor will also modify the value of
    
  766.     ``reason_phrase``.
    
  767. 
    
  768. .. attribute:: HttpResponse.reason_phrase
    
  769. 
    
  770.     The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's
    
  771.     <7231#section-6.1>` default reason phrases.
    
  772. 
    
  773.     Unless explicitly set, ``reason_phrase`` is determined by the value of
    
  774.     :attr:`status_code`.
    
  775. 
    
  776. .. attribute:: HttpResponse.streaming
    
  777. 
    
  778.     This is always ``False``.
    
  779. 
    
  780.     This attribute exists so middleware can treat streaming responses
    
  781.     differently from regular responses.
    
  782. 
    
  783. .. attribute:: HttpResponse.closed
    
  784. 
    
  785.     ``True`` if the response has been closed.
    
  786. 
    
  787. Methods
    
  788. -------
    
  789. 
    
  790. .. method:: HttpResponse.__init__(content=b'', content_type=None, status=200, reason=None, charset=None, headers=None)
    
  791. 
    
  792.     Instantiates an ``HttpResponse`` object with the given page content,
    
  793.     content type, and headers.
    
  794. 
    
  795.     ``content`` is most commonly an iterator, bytestring, :class:`memoryview`,
    
  796.     or string. Other types will be converted to a bytestring by encoding their
    
  797.     string representation. Iterators should return strings or bytestrings and
    
  798.     those will be joined together to form the content of the response.
    
  799. 
    
  800.     ``content_type`` is the MIME type optionally completed by a character set
    
  801.     encoding and is used to fill the HTTP ``Content-Type`` header. If not
    
  802.     specified, it is formed by ``'text/html'`` and the
    
  803.     :setting:`DEFAULT_CHARSET` settings, by default:
    
  804.     ``"text/html; charset=utf-8"``.
    
  805. 
    
  806.     ``status`` is the :rfc:`HTTP status code <7231#section-6>` for the response.
    
  807.     You can use Python's :py:class:`http.HTTPStatus` for meaningful aliases,
    
  808.     such as ``HTTPStatus.NO_CONTENT``.
    
  809. 
    
  810.     ``reason`` is the HTTP response phrase. If not provided, a default phrase
    
  811.     will be used.
    
  812. 
    
  813.     ``charset`` is the charset in which the response will be encoded. If not
    
  814.     given it will be extracted from ``content_type``, and if that
    
  815.     is unsuccessful, the :setting:`DEFAULT_CHARSET` setting will be used.
    
  816. 
    
  817.     ``headers`` is a :class:`dict` of HTTP headers for the response.
    
  818. 
    
  819. .. method:: HttpResponse.__setitem__(header, value)
    
  820. 
    
  821.     Sets the given header name to the given value. Both ``header`` and
    
  822.     ``value`` should be strings.
    
  823. 
    
  824. .. method:: HttpResponse.__delitem__(header)
    
  825. 
    
  826.     Deletes the header with the given name. Fails silently if the header
    
  827.     doesn't exist. Case-insensitive.
    
  828. 
    
  829. .. method:: HttpResponse.__getitem__(header)
    
  830. 
    
  831.     Returns the value for the given header name. Case-insensitive.
    
  832. 
    
  833. .. method:: HttpResponse.get(header, alternate=None)
    
  834. 
    
  835.     Returns the value for the given header, or an ``alternate`` if the header
    
  836.     doesn't exist.
    
  837. 
    
  838. .. method:: HttpResponse.has_header(header)
    
  839. 
    
  840.     Returns ``True`` or ``False`` based on a case-insensitive check for a
    
  841.     header with the given name.
    
  842. 
    
  843. .. method:: HttpResponse.items()
    
  844. 
    
  845.     Acts like :meth:`dict.items` for HTTP headers on the response.
    
  846. 
    
  847. .. method:: HttpResponse.setdefault(header, value)
    
  848. 
    
  849.     Sets a header unless it has already been set.
    
  850. 
    
  851. .. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
    
  852. 
    
  853.     Sets a cookie. The parameters are the same as in the
    
  854.     :class:`~http.cookies.Morsel` cookie object in the Python standard library.
    
  855. 
    
  856.     * ``max_age`` should be a :class:`~datetime.timedelta` object, an integer
    
  857.       number of seconds, or ``None`` (default) if the cookie should last only
    
  858.       as long as the client's browser session. If ``expires`` is not specified,
    
  859.       it will be calculated.
    
  860. 
    
  861.       .. versionchanged:: 4.1
    
  862. 
    
  863.         Support for ``timedelta`` objects was added.
    
  864. 
    
  865.     * ``expires`` should either be a string in the format
    
  866.       ``"Wdy, DD-Mon-YY HH:MM:SS GMT"`` or a ``datetime.datetime`` object
    
  867.       in UTC. If ``expires`` is a ``datetime`` object, the ``max_age``
    
  868.       will be calculated.
    
  869.     * Use ``domain`` if you want to set a cross-domain cookie. For example,
    
  870.       ``domain="example.com"`` will set a cookie that is readable by the
    
  871.       domains www.example.com, blog.example.com, etc. Otherwise, a cookie will
    
  872.       only be readable by the domain that set it.
    
  873.     * Use ``secure=True`` if you want the cookie to be only sent to the server
    
  874.       when a request is made with the ``https`` scheme.
    
  875.     * Use ``httponly=True`` if you want to prevent client-side
    
  876.       JavaScript from having access to the cookie.
    
  877. 
    
  878.       HttpOnly_ is a flag included in a Set-Cookie HTTP response header. It's
    
  879.       part of the :rfc:`RFC 6265 <6265#section-4.1.2.6>` standard for cookies
    
  880.       and can be a useful way to mitigate the risk of a client-side script
    
  881.       accessing the protected cookie data.
    
  882.     * Use ``samesite='Strict'`` or ``samesite='Lax'`` to tell the browser not
    
  883.       to send this cookie when performing a cross-origin request. `SameSite`_
    
  884.       isn't supported by all browsers, so it's not a replacement for Django's
    
  885.       CSRF protection, but rather a defense in depth measure.
    
  886. 
    
  887.       Use ``samesite='None'`` (string) to explicitly state that this cookie is
    
  888.       sent with all same-site and cross-site requests.
    
  889. 
    
  890.     .. _HttpOnly: https://owasp.org/www-community/HttpOnly
    
  891.     .. _SameSite: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
    
  892. 
    
  893.     .. warning::
    
  894. 
    
  895.         :rfc:`RFC 6265 <6265#section-6.1>` states that user agents should
    
  896.         support cookies of at least 4096 bytes. For many browsers this is also
    
  897.         the maximum size. Django will not raise an exception if there's an
    
  898.         attempt to store a cookie of more than 4096 bytes, but many browsers
    
  899.         will not set the cookie correctly.
    
  900. 
    
  901. .. method:: HttpResponse.set_signed_cookie(key, value, salt='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
    
  902. 
    
  903.     Like :meth:`~HttpResponse.set_cookie()`, but
    
  904.     :doc:`cryptographic signing </topics/signing>` the cookie before setting
    
  905.     it. Use in conjunction with :meth:`HttpRequest.get_signed_cookie`.
    
  906.     You can use the optional ``salt`` argument for added key strength, but
    
  907.     you will need to remember to pass it to the corresponding
    
  908.     :meth:`HttpRequest.get_signed_cookie` call.
    
  909. 
    
  910. .. method:: HttpResponse.delete_cookie(key, path='/', domain=None, samesite=None)
    
  911. 
    
  912.     Deletes the cookie with the given key. Fails silently if the key doesn't
    
  913.     exist.
    
  914. 
    
  915.     Due to the way cookies work, ``path`` and ``domain`` should be the same
    
  916.     values you used in ``set_cookie()`` -- otherwise the cookie may not be
    
  917.     deleted.
    
  918. 
    
  919. .. method:: HttpResponse.close()
    
  920. 
    
  921.     This method is called at the end of the request directly by the WSGI
    
  922.     server.
    
  923. 
    
  924. .. method:: HttpResponse.write(content)
    
  925. 
    
  926.     This method makes an :class:`HttpResponse` instance a file-like object.
    
  927. 
    
  928. .. method:: HttpResponse.flush()
    
  929. 
    
  930.     This method makes an :class:`HttpResponse` instance a file-like object.
    
  931. 
    
  932. .. method:: HttpResponse.tell()
    
  933. 
    
  934.     This method makes an :class:`HttpResponse` instance a file-like object.
    
  935. 
    
  936. .. method:: HttpResponse.getvalue()
    
  937. 
    
  938.     Returns the value of :attr:`HttpResponse.content`. This method makes
    
  939.     an :class:`HttpResponse` instance a stream-like object.
    
  940. 
    
  941. .. method:: HttpResponse.readable()
    
  942. 
    
  943.     Always ``False``. This method makes an :class:`HttpResponse` instance a
    
  944.     stream-like object.
    
  945. 
    
  946. .. method:: HttpResponse.seekable()
    
  947. 
    
  948.     Always ``False``. This method makes an :class:`HttpResponse` instance a
    
  949.     stream-like object.
    
  950. 
    
  951. .. method:: HttpResponse.writable()
    
  952. 
    
  953.     Always ``True``. This method makes an :class:`HttpResponse` instance a
    
  954.     stream-like object.
    
  955. 
    
  956. .. method:: HttpResponse.writelines(lines)
    
  957. 
    
  958.     Writes a list of lines to the response. Line separators are not added. This
    
  959.     method makes an :class:`HttpResponse` instance a stream-like object.
    
  960. 
    
  961. .. _ref-httpresponse-subclasses:
    
  962. 
    
  963. ``HttpResponse`` subclasses
    
  964. ---------------------------
    
  965. 
    
  966. Django includes a number of ``HttpResponse`` subclasses that handle different
    
  967. types of HTTP responses. Like ``HttpResponse``, these subclasses live in
    
  968. :mod:`django.http`.
    
  969. 
    
  970. .. class:: HttpResponseRedirect
    
  971. 
    
  972.     The first argument to the constructor is required -- the path to redirect
    
  973.     to. This can be a fully qualified URL
    
  974.     (e.g. ``'https://www.yahoo.com/search/'``), an absolute path with no domain
    
  975.     (e.g. ``'/search/'``), or even a relative path (e.g. ``'search/'``). In that
    
  976.     last case, the client browser will reconstruct the full URL itself
    
  977.     according to the current path. See :class:`HttpResponse` for other optional
    
  978.     constructor arguments. Note that this returns an HTTP status code 302.
    
  979. 
    
  980.     .. attribute:: HttpResponseRedirect.url
    
  981. 
    
  982.         This read-only attribute represents the URL the response will redirect
    
  983.         to (equivalent to the ``Location`` response header).
    
  984. 
    
  985. .. class:: HttpResponsePermanentRedirect
    
  986. 
    
  987.     Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
    
  988.     (HTTP status code 301) instead of a "found" redirect (status code 302).
    
  989. 
    
  990. .. class:: HttpResponseNotModified
    
  991. 
    
  992.     The constructor doesn't take any arguments and no content should be added
    
  993.     to this response. Use this to designate that a page hasn't been modified
    
  994.     since the user's last request (status code 304).
    
  995. 
    
  996. .. class:: HttpResponseBadRequest
    
  997. 
    
  998.     Acts just like :class:`HttpResponse` but uses a 400 status code.
    
  999. 
    
  1000. .. class:: HttpResponseNotFound
    
  1001. 
    
  1002.     Acts just like :class:`HttpResponse` but uses a 404 status code.
    
  1003. 
    
  1004. .. class:: HttpResponseForbidden
    
  1005. 
    
  1006.     Acts just like :class:`HttpResponse` but uses a 403 status code.
    
  1007. 
    
  1008. .. class:: HttpResponseNotAllowed
    
  1009. 
    
  1010.     Like :class:`HttpResponse`, but uses a 405 status code. The first argument
    
  1011.     to the constructor is required: a list of permitted methods (e.g.
    
  1012.     ``['GET', 'POST']``).
    
  1013. 
    
  1014. .. class:: HttpResponseGone
    
  1015. 
    
  1016.     Acts just like :class:`HttpResponse` but uses a 410 status code.
    
  1017. 
    
  1018. .. class:: HttpResponseServerError
    
  1019. 
    
  1020.     Acts just like :class:`HttpResponse` but uses a 500 status code.
    
  1021. 
    
  1022. .. note::
    
  1023. 
    
  1024.     If a custom subclass of :class:`HttpResponse` implements a ``render``
    
  1025.     method, Django will treat it as emulating a
    
  1026.     :class:`~django.template.response.SimpleTemplateResponse`, and the
    
  1027.     ``render`` method must itself return a valid response object.
    
  1028. 
    
  1029. Custom response classes
    
  1030. ~~~~~~~~~~~~~~~~~~~~~~~
    
  1031. 
    
  1032. If you find yourself needing a response class that Django doesn't provide, you
    
  1033. can create it with the help of :py:class:`http.HTTPStatus`. For example::
    
  1034. 
    
  1035.     from http import HTTPStatus
    
  1036.     from django.http import HttpResponse
    
  1037. 
    
  1038.     class HttpResponseNoContent(HttpResponse):
    
  1039.         status_code = HTTPStatus.NO_CONTENT
    
  1040. 
    
  1041. ``JsonResponse`` objects
    
  1042. ========================
    
  1043. 
    
  1044. .. class:: JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
    
  1045. 
    
  1046.     An :class:`HttpResponse` subclass that helps to create a JSON-encoded
    
  1047.     response. It inherits most behavior from its superclass with a couple
    
  1048.     differences:
    
  1049. 
    
  1050.     Its default ``Content-Type`` header is set to :mimetype:`application/json`.
    
  1051. 
    
  1052.     The first parameter, ``data``, should be a ``dict`` instance. If the
    
  1053.     ``safe`` parameter is set to ``False`` (see below) it can be any
    
  1054.     JSON-serializable object.
    
  1055. 
    
  1056.     The ``encoder``, which defaults to
    
  1057.     :class:`django.core.serializers.json.DjangoJSONEncoder`, will be used to
    
  1058.     serialize the data. See :ref:`JSON serialization
    
  1059.     <serialization-formats-json>` for more details about this serializer.
    
  1060. 
    
  1061.     The ``safe`` boolean parameter defaults to ``True``. If it's set to
    
  1062.     ``False``, any object can be passed for serialization (otherwise only
    
  1063.     ``dict`` instances are allowed). If ``safe`` is ``True`` and a non-``dict``
    
  1064.     object is passed as the first argument, a :exc:`TypeError` will be raised.
    
  1065. 
    
  1066.     The ``json_dumps_params`` parameter is a dictionary of keyword arguments
    
  1067.     to pass to the ``json.dumps()`` call used to generate the response.
    
  1068. 
    
  1069. Usage
    
  1070. -----
    
  1071. 
    
  1072. Typical usage could look like::
    
  1073. 
    
  1074.     >>> from django.http import JsonResponse
    
  1075.     >>> response = JsonResponse({'foo': 'bar'})
    
  1076.     >>> response.content
    
  1077.     b'{"foo": "bar"}'
    
  1078. 
    
  1079. Serializing non-dictionary objects
    
  1080. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1081. 
    
  1082. In order to serialize objects other than ``dict`` you must set the ``safe``
    
  1083. parameter to ``False``::
    
  1084. 
    
  1085.     >>> response = JsonResponse([1, 2, 3], safe=False)
    
  1086. 
    
  1087. Without passing ``safe=False``, a :exc:`TypeError` will be raised.
    
  1088. 
    
  1089. Note that an API based on ``dict`` objects is more extensible, flexible, and
    
  1090. makes it easier to maintain forwards compatibility. Therefore, you should avoid
    
  1091. using non-dict objects in JSON-encoded response.
    
  1092. 
    
  1093. .. warning::
    
  1094. 
    
  1095.     Before the `5th edition of ECMAScript
    
  1096.     <https://262.ecma-international.org/5.1/#sec-11.1.4>`_ it was possible to
    
  1097.     poison the JavaScript ``Array`` constructor. For this reason, Django does
    
  1098.     not allow passing non-dict objects to the
    
  1099.     :class:`~django.http.JsonResponse` constructor by default.  However, most
    
  1100.     modern browsers implement ECMAScript 5 which removes this attack vector.
    
  1101.     Therefore it is possible to disable this security precaution.
    
  1102. 
    
  1103. Changing the default JSON encoder
    
  1104. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1105. 
    
  1106. If you need to use a different JSON encoder class you can pass the ``encoder``
    
  1107. parameter to the constructor method::
    
  1108. 
    
  1109.     >>> response = JsonResponse(data, encoder=MyJSONEncoder)
    
  1110. 
    
  1111. .. _httpresponse-streaming:
    
  1112. 
    
  1113. ``StreamingHttpResponse`` objects
    
  1114. =================================
    
  1115. 
    
  1116. .. class:: StreamingHttpResponse
    
  1117. 
    
  1118. The :class:`StreamingHttpResponse` class is used to stream a response from
    
  1119. Django to the browser. You might want to do this if generating the response
    
  1120. takes too long or uses too much memory. For instance, it's useful for
    
  1121. :ref:`generating large CSV files <streaming-csv-files>`.
    
  1122. 
    
  1123. .. admonition:: Performance considerations
    
  1124. 
    
  1125.     Django is designed for short-lived requests. Streaming responses will tie
    
  1126.     a worker process for the entire duration of the response. This may result
    
  1127.     in poor performance.
    
  1128. 
    
  1129.     Generally speaking, you should perform expensive tasks outside of the
    
  1130.     request-response cycle, rather than resorting to a streamed response.
    
  1131. 
    
  1132. The :class:`StreamingHttpResponse` is not a subclass of :class:`HttpResponse`,
    
  1133. because it features a slightly different API. However, it is almost identical,
    
  1134. with the following notable differences:
    
  1135. 
    
  1136. * It should be given an iterator that yields bytestrings as content.
    
  1137. 
    
  1138. * You cannot access its content, except by iterating the response object
    
  1139.   itself. This should only occur when the response is returned to the client.
    
  1140. 
    
  1141. * It has no ``content`` attribute. Instead, it has a
    
  1142.   :attr:`~StreamingHttpResponse.streaming_content` attribute.
    
  1143. 
    
  1144. * You cannot use the file-like object ``tell()`` or ``write()`` methods.
    
  1145.   Doing so will raise an exception.
    
  1146. 
    
  1147. :class:`StreamingHttpResponse` should only be used in situations where it is
    
  1148. absolutely required that the whole content isn't iterated before transferring
    
  1149. the data to the client. Because the content can't be accessed, many
    
  1150. middleware can't function normally. For example the ``ETag`` and
    
  1151. ``Content-Length`` headers can't be generated for streaming responses.
    
  1152. 
    
  1153. The :class:`HttpResponseBase` base class is common between
    
  1154. :class:`HttpResponse` and :class:`StreamingHttpResponse`.
    
  1155. 
    
  1156. Attributes
    
  1157. ----------
    
  1158. 
    
  1159. .. attribute:: StreamingHttpResponse.streaming_content
    
  1160. 
    
  1161.     An iterator of the response content, bytestring encoded according to
    
  1162.     :attr:`HttpResponse.charset`.
    
  1163. 
    
  1164. .. attribute:: StreamingHttpResponse.status_code
    
  1165. 
    
  1166.     The :rfc:`HTTP status code <7231#section-6>` for the response.
    
  1167. 
    
  1168.     Unless :attr:`reason_phrase` is explicitly set, modifying the value of
    
  1169.     ``status_code`` outside the constructor will also modify the value of
    
  1170.     ``reason_phrase``.
    
  1171. 
    
  1172. .. attribute:: StreamingHttpResponse.reason_phrase
    
  1173. 
    
  1174.     The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's
    
  1175.     <7231#section-6.1>` default reason phrases.
    
  1176. 
    
  1177.     Unless explicitly set, ``reason_phrase`` is determined by the value of
    
  1178.     :attr:`status_code`.
    
  1179. 
    
  1180. .. attribute:: StreamingHttpResponse.streaming
    
  1181. 
    
  1182.     This is always ``True``.
    
  1183. 
    
  1184. ``FileResponse`` objects
    
  1185. ========================
    
  1186. 
    
  1187. .. class:: FileResponse(open_file, as_attachment=False, filename='', **kwargs)
    
  1188. 
    
  1189.     :class:`FileResponse` is a subclass of :class:`StreamingHttpResponse`
    
  1190.     optimized for binary files. It uses :pep:`wsgi.file_wrapper
    
  1191.     <3333#optional-platform-specific-file-handling>` if provided by the wsgi
    
  1192.     server, otherwise it streams the file out in small chunks.
    
  1193. 
    
  1194.     If ``as_attachment=True``, the ``Content-Disposition`` header is set to
    
  1195.     ``attachment``, which asks the browser to offer the file to the user as a
    
  1196.     download. Otherwise, a ``Content-Disposition`` header with a value of
    
  1197.     ``inline`` (the browser default) will be set only if a filename is
    
  1198.     available.
    
  1199. 
    
  1200.     If ``open_file`` doesn't have a name or if the name of ``open_file`` isn't
    
  1201.     appropriate, provide a custom file name using the ``filename``  parameter.
    
  1202.     Note that if you pass a file-like object like ``io.BytesIO``, it's your
    
  1203.     task to ``seek()`` it before passing it to ``FileResponse``.
    
  1204. 
    
  1205.     The ``Content-Length`` and ``Content-Type`` headers are automatically set
    
  1206.     when they can be guessed from contents of ``open_file``.
    
  1207. 
    
  1208. ``FileResponse`` accepts any file-like object with binary content, for example
    
  1209. a file open in binary mode like so::
    
  1210. 
    
  1211.     >>> from django.http import FileResponse
    
  1212.     >>> response = FileResponse(open('myfile.png', 'rb'))
    
  1213. 
    
  1214. The file will be closed automatically, so don't open it with a context manager.
    
  1215. 
    
  1216. Methods
    
  1217. -------
    
  1218. 
    
  1219. .. method:: FileResponse.set_headers(open_file)
    
  1220. 
    
  1221.     This method is automatically called during the response initialization and
    
  1222.     set various headers (``Content-Length``, ``Content-Type``, and
    
  1223.     ``Content-Disposition``) depending on ``open_file``.
    
  1224. 
    
  1225. ``HttpResponseBase`` class
    
  1226. ==========================
    
  1227. 
    
  1228. .. class:: HttpResponseBase
    
  1229. 
    
  1230. The :class:`HttpResponseBase` class is common to all Django responses.
    
  1231. It should not be used to create responses directly, but it can be
    
  1232. useful for type-checking.