"Fossies" - the Fresh Open Source Software Archive

Member "Django-1.11.25/docs/ref/request-response.txt" (1 Oct 2019, 40724 Bytes) of package /linux/www/Django-1.11.25.tar.gz:


As a special service "Fossies" has tried to format the requested text file into HTML format (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the last Fossies "Diffs" side-by-side code changes report for "request-response.txt": 2.2.5_vs_2.2.6.

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