request-response.txt 42 KB

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