request-response.txt 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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-prefixed
  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. Like :meth:`get_full_path`, but uses :attr:`path_info` instead of
  232. :attr:`path`.
  233. Example: ``"/minfo/music/bands/the_beatles/?print=true"``
  234. .. method:: HttpRequest.build_absolute_uri(location=None)
  235. Returns the absolute URI form of ``location``. If no location is provided,
  236. the location will be set to ``request.get_full_path()``.
  237. If the location is already an absolute URI, it will not be altered.
  238. Otherwise the absolute URI is built using the server variables available in
  239. this request. For example:
  240. >>> request.build_absolute_uri()
  241. 'https://example.com/music/bands/the_beatles/?print=true'
  242. >>> request.build_absolute_uri('/bands/')
  243. 'https://example.com/bands/'
  244. >>> request.build_absolute_uri('https://example2.com/bands/')
  245. 'https://example2.com/bands/'
  246. .. note::
  247. Mixing HTTP and HTTPS on the same site is discouraged, therefore
  248. :meth:`~HttpRequest.build_absolute_uri()` will always generate an
  249. absolute URI with the same scheme the current request has. If you need
  250. to redirect users to HTTPS, it's best to let your Web server redirect
  251. all HTTP traffic to HTTPS.
  252. .. method:: HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
  253. Returns a cookie value for a signed cookie, or raises a
  254. ``django.core.signing.BadSignature`` exception if the signature is
  255. no longer valid. If you provide the ``default`` argument the exception
  256. will be suppressed and that default value will be returned instead.
  257. The optional ``salt`` argument can be used to provide extra protection
  258. against brute force attacks on your secret key. If supplied, the
  259. ``max_age`` argument will be checked against the signed timestamp
  260. attached to the cookie value to ensure the cookie is not older than
  261. ``max_age`` seconds.
  262. For example::
  263. >>> request.get_signed_cookie('name')
  264. 'Tony'
  265. >>> request.get_signed_cookie('name', salt='name-salt')
  266. 'Tony' # assuming cookie was set using the same salt
  267. >>> request.get_signed_cookie('nonexistent-cookie')
  268. ...
  269. KeyError: 'nonexistent-cookie'
  270. >>> request.get_signed_cookie('nonexistent-cookie', False)
  271. False
  272. >>> request.get_signed_cookie('cookie-that-was-tampered-with')
  273. ...
  274. BadSignature: ...
  275. >>> request.get_signed_cookie('name', max_age=60)
  276. ...
  277. SignatureExpired: Signature age 1677.3839159 > 60 seconds
  278. >>> request.get_signed_cookie('name', False, max_age=60)
  279. False
  280. See :doc:`cryptographic signing </topics/signing>` for more information.
  281. .. method:: HttpRequest.is_secure()
  282. Returns ``True`` if the request is secure; that is, if it was made with
  283. HTTPS.
  284. .. method:: HttpRequest.is_ajax()
  285. Returns ``True`` if the request was made via an ``XMLHttpRequest``, by
  286. checking the ``HTTP_X_REQUESTED_WITH`` header for the string
  287. ``'XMLHttpRequest'``. Most modern JavaScript libraries send this header.
  288. If you write your own ``XMLHttpRequest`` call (on the browser side), you'll
  289. have to set this header manually if you want ``is_ajax()`` to work.
  290. If a response varies on whether or not it's requested via AJAX and you are
  291. using some form of caching like Django's :mod:`cache middleware
  292. <django.middleware.cache>`, you should decorate the view with
  293. :func:`vary_on_headers('X-Requested-With')
  294. <django.views.decorators.vary.vary_on_headers>` so that the responses are
  295. properly cached.
  296. .. method:: HttpRequest.read(size=None)
  297. .. method:: HttpRequest.readline()
  298. .. method:: HttpRequest.readlines()
  299. .. method:: HttpRequest.__iter__()
  300. Methods implementing a file-like interface for reading from an
  301. ``HttpRequest`` instance. This makes it possible to consume an incoming
  302. request in a streaming fashion. A common use-case would be to process a
  303. big XML payload with an iterative parser without constructing a whole
  304. XML tree in memory.
  305. Given this standard interface, an ``HttpRequest`` instance can be
  306. passed directly to an XML parser such as
  307. :class:`~xml.etree.ElementTree.ElementTree`::
  308. import xml.etree.ElementTree as ET
  309. for element in ET.iterparse(request):
  310. process(element)
  311. ``QueryDict`` objects
  312. =====================
  313. .. class:: QueryDict
  314. In an :class:`HttpRequest` object, the :attr:`~HttpRequest.GET` and
  315. :attr:`~HttpRequest.POST` attributes are instances of ``django.http.QueryDict``,
  316. a dictionary-like class customized to deal with multiple values for the same
  317. key. This is necessary because some HTML form elements, notably
  318. ``<select multiple>``, pass multiple values for the same key.
  319. The ``QueryDict``\ s at ``request.POST`` and ``request.GET`` will be immutable
  320. when accessed in a normal request/response cycle. To get a mutable version you
  321. need to use :meth:`QueryDict.copy`.
  322. Methods
  323. -------
  324. :class:`QueryDict` implements all the standard dictionary methods because it's
  325. a subclass of dictionary. Exceptions are outlined here:
  326. .. method:: QueryDict.__init__(query_string=None, mutable=False, encoding=None)
  327. Instantiates a ``QueryDict`` object based on ``query_string``.
  328. >>> QueryDict('a=1&a=2&c=3')
  329. <QueryDict: {'a': ['1', '2'], 'c': ['3']}>
  330. If ``query_string`` is not passed in, the resulting ``QueryDict`` will be
  331. empty (it will have no keys or values).
  332. Most ``QueryDict``\ s you encounter, and in particular those at
  333. ``request.POST`` and ``request.GET``, will be immutable. If you are
  334. instantiating one yourself, you can make it mutable by passing
  335. ``mutable=True`` to its ``__init__()``.
  336. Strings for setting both keys and values will be converted from ``encoding``
  337. to ``str``. If ``encoding`` is not set, it defaults to
  338. :setting:`DEFAULT_CHARSET`.
  339. .. classmethod:: QueryDict.fromkeys(iterable, value='', mutable=False, encoding=None)
  340. Creates a new ``QueryDict`` with keys from ``iterable`` and each value
  341. equal to ``value``. For example::
  342. >>> QueryDict.fromkeys(['a', 'a', 'b'], value='val')
  343. <QueryDict: {'a': ['val', 'val'], 'b': ['val']}>
  344. .. method:: QueryDict.__getitem__(key)
  345. Returns the value for the given key. If the key has more than one value,
  346. it returns the last value. Raises
  347. ``django.utils.datastructures.MultiValueDictKeyError`` if the key does not
  348. exist. (This is a subclass of Python's standard :exc:`KeyError`, so you can
  349. stick to catching ``KeyError``.)
  350. .. method:: QueryDict.__setitem__(key, value)
  351. Sets the given key to ``[value]`` (a list whose single element is
  352. ``value``). Note that this, as other dictionary functions that have side
  353. effects, can only be called on a mutable ``QueryDict`` (such as one that
  354. was created via :meth:`QueryDict.copy`).
  355. .. method:: QueryDict.__contains__(key)
  356. Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
  357. in request.GET``.
  358. .. method:: QueryDict.get(key, default=None)
  359. Uses the same logic as :meth:`__getitem__`, with a hook for returning a
  360. default value if the key doesn't exist.
  361. .. method:: QueryDict.setdefault(key, default=None)
  362. Like :meth:`dict.setdefault`, except it uses :meth:`__setitem__` internally.
  363. .. method:: QueryDict.update(other_dict)
  364. Takes either a ``QueryDict`` or a dictionary. Like :meth:`dict.update`,
  365. except it *appends* to the current dictionary items rather than replacing
  366. them. For example::
  367. >>> q = QueryDict('a=1', mutable=True)
  368. >>> q.update({'a': '2'})
  369. >>> q.getlist('a')
  370. ['1', '2']
  371. >>> q['a'] # returns the last
  372. '2'
  373. .. method:: QueryDict.items()
  374. Like :meth:`dict.items`, except this uses the same last-value logic as
  375. :meth:`__getitem__` and returns an iterator object instead of a view object.
  376. For example::
  377. >>> q = QueryDict('a=1&a=2&a=3')
  378. >>> list(q.items())
  379. [('a', '3')]
  380. .. method:: QueryDict.values()
  381. Like :meth:`dict.values`, except this uses the same last-value logic as
  382. :meth:`__getitem__` and returns an iterator instead of a view object. For
  383. example::
  384. >>> q = QueryDict('a=1&a=2&a=3')
  385. >>> list(q.values())
  386. ['3']
  387. In addition, ``QueryDict`` has the following methods:
  388. .. method:: QueryDict.copy()
  389. Returns a copy of the object using :func:`copy.deepcopy`. This copy will
  390. be mutable even if the original was not.
  391. .. method:: QueryDict.getlist(key, default=None)
  392. Returns a list of the data with the requested key. Returns an empty list if
  393. the key doesn't exist and a default value wasn't provided. It's guaranteed
  394. to return a list unless the default value provided isn't a list.
  395. .. method:: QueryDict.setlist(key, list_)
  396. Sets the given key to ``list_`` (unlike :meth:`__setitem__`).
  397. .. method:: QueryDict.appendlist(key, item)
  398. Appends an item to the internal list associated with key.
  399. .. method:: QueryDict.setlistdefault(key, default_list=None)
  400. Like :meth:`setdefault`, except it takes a list of values instead of a
  401. single value.
  402. .. method:: QueryDict.lists()
  403. Like :meth:`items()`, except it includes all values, as a list, for each
  404. member of the dictionary. For example::
  405. >>> q = QueryDict('a=1&a=2&a=3')
  406. >>> q.lists()
  407. [('a', ['1', '2', '3'])]
  408. .. method:: QueryDict.pop(key)
  409. Returns a list of values for the given key and removes them from the
  410. dictionary. Raises ``KeyError`` if the key does not exist. For example::
  411. >>> q = QueryDict('a=1&a=2&a=3', mutable=True)
  412. >>> q.pop('a')
  413. ['1', '2', '3']
  414. .. method:: QueryDict.popitem()
  415. Removes an arbitrary member of the dictionary (since there's no concept
  416. of ordering), and returns a two value tuple containing the key and a list
  417. of all values for the key. Raises ``KeyError`` when called on an empty
  418. dictionary. For example::
  419. >>> q = QueryDict('a=1&a=2&a=3', mutable=True)
  420. >>> q.popitem()
  421. ('a', ['1', '2', '3'])
  422. .. method:: QueryDict.dict()
  423. Returns a ``dict`` representation of ``QueryDict``. For every (key, list)
  424. pair in ``QueryDict``, ``dict`` will have (key, item), where item is one
  425. element of the list, using the same logic as :meth:`QueryDict.__getitem__`::
  426. >>> q = QueryDict('a=1&a=3&a=5')
  427. >>> q.dict()
  428. {'a': '5'}
  429. .. method:: QueryDict.urlencode(safe=None)
  430. Returns a string of the data in query string format. For example::
  431. >>> q = QueryDict('a=2&b=3&b=5')
  432. >>> q.urlencode()
  433. 'a=2&b=3&b=5'
  434. Use the ``safe`` parameter to pass characters which don't require encoding.
  435. For example::
  436. >>> q = QueryDict(mutable=True)
  437. >>> q['next'] = '/a&b/'
  438. >>> q.urlencode(safe='/')
  439. 'next=/a%26b/'
  440. ``HttpResponse`` objects
  441. ========================
  442. .. class:: HttpResponse
  443. In contrast to :class:`HttpRequest` objects, which are created automatically by
  444. Django, :class:`HttpResponse` objects are your responsibility. Each view you
  445. write is responsible for instantiating, populating, and returning an
  446. :class:`HttpResponse`.
  447. The :class:`HttpResponse` class lives in the :mod:`django.http` module.
  448. Usage
  449. -----
  450. Passing strings
  451. ~~~~~~~~~~~~~~~
  452. Typical usage is to pass the contents of the page, as a string, to the
  453. :class:`HttpResponse` constructor::
  454. >>> from django.http import HttpResponse
  455. >>> response = HttpResponse("Here's the text of the Web page.")
  456. >>> response = HttpResponse("Text only, please.", content_type="text/plain")
  457. But if you want to add content incrementally, you can use ``response`` as a
  458. file-like object::
  459. >>> response = HttpResponse()
  460. >>> response.write("<p>Here's the text of the Web page.</p>")
  461. >>> response.write("<p>Here's another paragraph.</p>")
  462. Passing iterators
  463. ~~~~~~~~~~~~~~~~~
  464. Finally, you can pass ``HttpResponse`` an iterator rather than strings.
  465. ``HttpResponse`` will consume the iterator immediately, store its content as a
  466. string, and discard it. Objects with a ``close()`` method such as files and
  467. generators are immediately closed.
  468. If you need the response to be streamed from the iterator to the client, you
  469. must use the :class:`StreamingHttpResponse` class instead.
  470. Setting header fields
  471. ~~~~~~~~~~~~~~~~~~~~~
  472. To set or remove a header field in your response, treat it like a dictionary::
  473. >>> response = HttpResponse()
  474. >>> response['Age'] = 120
  475. >>> del response['Age']
  476. Note that unlike a dictionary, ``del`` doesn't raise ``KeyError`` if the header
  477. field doesn't exist.
  478. For setting the ``Cache-Control`` and ``Vary`` header fields, it is recommended
  479. to use the :func:`~django.utils.cache.patch_cache_control` and
  480. :func:`~django.utils.cache.patch_vary_headers` methods from
  481. :mod:`django.utils.cache`, since these fields can have multiple, comma-separated
  482. values. The "patch" methods ensure that other values, e.g. added by a
  483. middleware, are not removed.
  484. HTTP header fields cannot contain newlines. An attempt to set a header field
  485. containing a newline character (CR or LF) will raise ``BadHeaderError``
  486. Telling the browser to treat the response as a file attachment
  487. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  488. To tell the browser to treat the response as a file attachment, use the
  489. ``content_type`` argument and set the ``Content-Disposition`` header. For example,
  490. this is how you might return a Microsoft Excel spreadsheet::
  491. >>> response = HttpResponse(my_data, content_type='application/vnd.ms-excel')
  492. >>> response['Content-Disposition'] = 'attachment; filename="foo.xls"'
  493. There's nothing Django-specific about the ``Content-Disposition`` header, but
  494. it's easy to forget the syntax, so we've included it here.
  495. Attributes
  496. ----------
  497. .. attribute:: HttpResponse.content
  498. A bytestring representing the content, encoded from a string if necessary.
  499. .. attribute:: HttpResponse.charset
  500. A string denoting the charset in which the response will be encoded. If not
  501. given at ``HttpResponse`` instantiation time, it will be extracted from
  502. ``content_type`` and if that is unsuccessful, the
  503. :setting:`DEFAULT_CHARSET` setting will be used.
  504. .. attribute:: HttpResponse.status_code
  505. The :rfc:`HTTP status code <7231#section-6>` for the response.
  506. Unless :attr:`reason_phrase` is explicitly set, modifying the value of
  507. ``status_code`` outside the constructor will also modify the value of
  508. ``reason_phrase``.
  509. .. attribute:: HttpResponse.reason_phrase
  510. The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's
  511. <7231#section-6.1>` default reason phrases.
  512. Unless explicitly set, ``reason_phrase`` is determined by the value of
  513. :attr:`status_code`.
  514. .. attribute:: HttpResponse.streaming
  515. This is always ``False``.
  516. This attribute exists so middleware can treat streaming responses
  517. differently from regular responses.
  518. .. attribute:: HttpResponse.closed
  519. ``True`` if the response has been closed.
  520. Methods
  521. -------
  522. .. method:: HttpResponse.__init__(content='', content_type=None, status=200, reason=None, charset=None)
  523. Instantiates an ``HttpResponse`` object with the given page content and
  524. content type.
  525. ``content`` should be an iterator or a string. If it's an
  526. iterator, it should return strings, and those strings will be
  527. joined together to form the content of the response. If it is not
  528. an iterator or a string, it will be converted to a string when
  529. accessed.
  530. ``content_type`` is the MIME type optionally completed by a character set
  531. encoding and is used to fill the HTTP ``Content-Type`` header. If not
  532. specified, it is formed by ``'text/html'`` and the
  533. :setting:`DEFAULT_CHARSET` settings, by default: "`text/html; charset=utf-8`".
  534. ``status`` is the :rfc:`HTTP status code <7231#section-6>` for the response.
  535. ``reason`` is the HTTP response phrase. If not provided, a default phrase
  536. will be used.
  537. ``charset`` is the charset in which the response will be encoded. If not
  538. given it will be extracted from ``content_type``, and if that
  539. is unsuccessful, the :setting:`DEFAULT_CHARSET` setting will be used.
  540. .. method:: HttpResponse.__setitem__(header, value)
  541. Sets the given header name to the given value. Both ``header`` and
  542. ``value`` should be strings.
  543. .. method:: HttpResponse.__delitem__(header)
  544. Deletes the header with the given name. Fails silently if the header
  545. doesn't exist. Case-insensitive.
  546. .. method:: HttpResponse.__getitem__(header)
  547. Returns the value for the given header name. Case-insensitive.
  548. .. method:: HttpResponse.has_header(header)
  549. Returns ``True`` or ``False`` based on a case-insensitive check for a
  550. header with the given name.
  551. .. method:: HttpResponse.setdefault(header, value)
  552. Sets a header unless it has already been set.
  553. .. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False, samesite=None)
  554. Sets a cookie. The parameters are the same as in the
  555. :class:`~http.cookies.Morsel` cookie object in the Python standard library.
  556. * ``max_age`` should be a number of seconds, or ``None`` (default) if
  557. the cookie should last only as long as the client's browser session.
  558. If ``expires`` is not specified, it will be calculated.
  559. * ``expires`` should either be a string in the format
  560. ``"Wdy, DD-Mon-YY HH:MM:SS GMT"`` or a ``datetime.datetime`` object
  561. in UTC. If ``expires`` is a ``datetime`` object, the ``max_age``
  562. will be calculated.
  563. * Use ``domain`` if you want to set a cross-domain cookie. For example,
  564. ``domain="example.com"`` will set a cookie that is readable by the
  565. domains www.example.com, blog.example.com, etc. Otherwise, a cookie will
  566. only be readable by the domain that set it.
  567. * Use ``httponly=True`` if you want to prevent client-side
  568. JavaScript from having access to the cookie.
  569. HTTPOnly_ is a flag included in a Set-Cookie HTTP response
  570. header. It is not part of the :rfc:`2109` standard for cookies,
  571. and it isn't honored consistently by all browsers. However,
  572. when it is honored, it can be a useful way to mitigate the
  573. risk of a client-side script from accessing the protected cookie
  574. data.
  575. * Use ``samesite='Strict'`` or ``samesite='Lax'`` to tell the browser not
  576. to send this cookie when performing a cross-origin request. `SameSite`_
  577. isn't supported by all browsers, so it's not a replacement for Django's
  578. CSRF protection, but rather a defense in depth measure.
  579. .. _HTTPOnly: https://www.owasp.org/index.php/HTTPOnly
  580. .. _SameSite: https://www.owasp.org/index.php/SameSite
  581. .. warning::
  582. Both :rfc:`2109` and :rfc:`6265` state that user agents should support
  583. cookies of at least 4096 bytes. For many browsers this is also the
  584. maximum size. Django will not raise an exception if there's an attempt
  585. to store a cookie of more than 4096 bytes, but many browsers will not
  586. set the cookie correctly.
  587. .. method:: HttpResponse.set_signed_cookie(key, value, salt='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False, samesite=None)
  588. Like :meth:`~HttpResponse.set_cookie()`, but
  589. :doc:`cryptographic signing </topics/signing>` the cookie before setting
  590. it. Use in conjunction with :meth:`HttpRequest.get_signed_cookie`.
  591. You can use the optional ``salt`` argument for added key strength, but
  592. you will need to remember to pass it to the corresponding
  593. :meth:`HttpRequest.get_signed_cookie` call.
  594. .. method:: HttpResponse.delete_cookie(key, path='/', domain=None)
  595. Deletes the cookie with the given key. Fails silently if the key doesn't
  596. exist.
  597. Due to the way cookies work, ``path`` and ``domain`` should be the same
  598. values you used in ``set_cookie()`` -- otherwise the cookie may not be
  599. deleted.
  600. .. method:: HttpResponse.write(content)
  601. This method makes an :class:`HttpResponse` instance a file-like object.
  602. .. method:: HttpResponse.flush()
  603. This method makes an :class:`HttpResponse` instance a file-like object.
  604. .. method:: HttpResponse.tell()
  605. This method makes an :class:`HttpResponse` instance a file-like object.
  606. .. method:: HttpResponse.getvalue()
  607. Returns the value of :attr:`HttpResponse.content`. This method makes
  608. an :class:`HttpResponse` instance a stream-like object.
  609. .. method:: HttpResponse.readable()
  610. Always ``False``. This method makes an :class:`HttpResponse` instance a
  611. stream-like object.
  612. .. method:: HttpResponse.seekable()
  613. Always ``False``. This method makes an :class:`HttpResponse` instance a
  614. stream-like object.
  615. .. method:: HttpResponse.writable()
  616. Always ``True``. This method makes an :class:`HttpResponse` instance a
  617. stream-like object.
  618. .. method:: HttpResponse.writelines(lines)
  619. Writes a list of lines to the response. Line separators are not added. This
  620. method makes an :class:`HttpResponse` instance a stream-like object.
  621. .. _ref-httpresponse-subclasses:
  622. ``HttpResponse`` subclasses
  623. ---------------------------
  624. Django includes a number of ``HttpResponse`` subclasses that handle different
  625. types of HTTP responses. Like ``HttpResponse``, these subclasses live in
  626. :mod:`django.http`.
  627. .. class:: HttpResponseRedirect
  628. The first argument to the constructor is required -- the path to redirect
  629. to. This can be a fully qualified URL
  630. (e.g. ``'https://www.yahoo.com/search/'``), an absolute path with no domain
  631. (e.g. ``'/search/'``), or even a relative path (e.g. ``'search/'``). In that
  632. last case, the client browser will reconstruct the full URL itself
  633. according to the current path. See :class:`HttpResponse` for other optional
  634. constructor arguments. Note that this returns an HTTP status code 302.
  635. .. attribute:: HttpResponseRedirect.url
  636. This read-only attribute represents the URL the response will redirect
  637. to (equivalent to the ``Location`` response header).
  638. .. class:: HttpResponsePermanentRedirect
  639. Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
  640. (HTTP status code 301) instead of a "found" redirect (status code 302).
  641. .. class:: HttpResponseNotModified
  642. The constructor doesn't take any arguments and no content should be added
  643. to this response. Use this to designate that a page hasn't been modified
  644. since the user's last request (status code 304).
  645. .. class:: HttpResponseBadRequest
  646. Acts just like :class:`HttpResponse` but uses a 400 status code.
  647. .. class:: HttpResponseNotFound
  648. Acts just like :class:`HttpResponse` but uses a 404 status code.
  649. .. class:: HttpResponseForbidden
  650. Acts just like :class:`HttpResponse` but uses a 403 status code.
  651. .. class:: HttpResponseNotAllowed
  652. Like :class:`HttpResponse`, but uses a 405 status code. The first argument
  653. to the constructor is required: a list of permitted methods (e.g.
  654. ``['GET', 'POST']``).
  655. .. class:: HttpResponseGone
  656. Acts just like :class:`HttpResponse` but uses a 410 status code.
  657. .. class:: HttpResponseServerError
  658. Acts just like :class:`HttpResponse` but uses a 500 status code.
  659. .. note::
  660. If a custom subclass of :class:`HttpResponse` implements a ``render``
  661. method, Django will treat it as emulating a
  662. :class:`~django.template.response.SimpleTemplateResponse`, and the
  663. ``render`` method must itself return a valid response object.
  664. ``JsonResponse`` objects
  665. ========================
  666. .. class:: JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
  667. An :class:`HttpResponse` subclass that helps to create a JSON-encoded
  668. response. It inherits most behavior from its superclass with a couple
  669. differences:
  670. Its default ``Content-Type`` header is set to ``application/json``.
  671. The first parameter, ``data``, should be a ``dict`` instance. If the
  672. ``safe`` parameter is set to ``False`` (see below) it can be any
  673. JSON-serializable object.
  674. The ``encoder``, which defaults to
  675. :class:`django.core.serializers.json.DjangoJSONEncoder`, will be used to
  676. serialize the data. See :ref:`JSON serialization
  677. <serialization-formats-json>` for more details about this serializer.
  678. The ``safe`` boolean parameter defaults to ``True``. If it's set to
  679. ``False``, any object can be passed for serialization (otherwise only
  680. ``dict`` instances are allowed). If ``safe`` is ``True`` and a non-``dict``
  681. object is passed as the first argument, a :exc:`TypeError` will be raised.
  682. The ``json_dumps_params`` parameter is a dictionary of keyword arguments
  683. to pass to the ``json.dumps()`` call used to generate the response.
  684. Usage
  685. -----
  686. Typical usage could look like::
  687. >>> from django.http import JsonResponse
  688. >>> response = JsonResponse({'foo': 'bar'})
  689. >>> response.content
  690. b'{"foo": "bar"}'
  691. Serializing non-dictionary objects
  692. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  693. In order to serialize objects other than ``dict`` you must set the ``safe``
  694. parameter to ``False``::
  695. >>> response = JsonResponse([1, 2, 3], safe=False)
  696. Without passing ``safe=False``, a :exc:`TypeError` will be raised.
  697. .. warning::
  698. Before the `5th edition of ECMAScript
  699. <https://www.ecma-international.org/ecma-262/5.1/index.html#sec-11.1.4>`_
  700. it was possible to poison the JavaScript ``Array`` constructor. For this
  701. reason, Django does not allow passing non-dict objects to the
  702. :class:`~django.http.JsonResponse` constructor by default. However, most
  703. modern browsers implement EcmaScript 5 which removes this attack vector.
  704. Therefore it is possible to disable this security precaution.
  705. Changing the default JSON encoder
  706. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  707. If you need to use a different JSON encoder class you can pass the ``encoder``
  708. parameter to the constructor method::
  709. >>> response = JsonResponse(data, encoder=MyJSONEncoder)
  710. .. _httpresponse-streaming:
  711. ``StreamingHttpResponse`` objects
  712. =================================
  713. .. class:: StreamingHttpResponse
  714. The :class:`StreamingHttpResponse` class is used to stream a response from
  715. Django to the browser. You might want to do this if generating the response
  716. takes too long or uses too much memory. For instance, it's useful for
  717. :ref:`generating large CSV files <streaming-csv-files>`.
  718. .. admonition:: Performance considerations
  719. Django is designed for short-lived requests. Streaming responses will tie
  720. a worker process for the entire duration of the response. This may result
  721. in poor performance.
  722. Generally speaking, you should perform expensive tasks outside of the
  723. request-response cycle, rather than resorting to a streamed response.
  724. The :class:`StreamingHttpResponse` is not a subclass of :class:`HttpResponse`,
  725. because it features a slightly different API. However, it is almost identical,
  726. with the following notable differences:
  727. * It should be given an iterator that yields strings as content.
  728. * You cannot access its content, except by iterating the response object
  729. itself. This should only occur when the response is returned to the client.
  730. * It has no ``content`` attribute. Instead, it has a
  731. :attr:`~StreamingHttpResponse.streaming_content` attribute.
  732. * You cannot use the file-like object ``tell()`` or ``write()`` methods.
  733. Doing so will raise an exception.
  734. :class:`StreamingHttpResponse` should only be used in situations where it is
  735. absolutely required that the whole content isn't iterated before transferring
  736. the data to the client. Because the content can't be accessed, many
  737. middleware can't function normally. For example the ``ETag`` and
  738. ``Content-Length`` headers can't be generated for streaming responses.
  739. Attributes
  740. ----------
  741. .. attribute:: StreamingHttpResponse.streaming_content
  742. An iterator of strings representing the content.
  743. .. attribute:: StreamingHttpResponse.status_code
  744. The :rfc:`HTTP status code <7231#section-6>` for the response.
  745. Unless :attr:`reason_phrase` is explicitly set, modifying the value of
  746. ``status_code`` outside the constructor will also modify the value of
  747. ``reason_phrase``.
  748. .. attribute:: StreamingHttpResponse.reason_phrase
  749. The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's
  750. <7231#section-6.1>` default reason phrases.
  751. Unless explicitly set, ``reason_phrase`` is determined by the value of
  752. :attr:`status_code`.
  753. .. attribute:: StreamingHttpResponse.streaming
  754. This is always ``True``.
  755. ``FileResponse`` objects
  756. ========================
  757. .. class:: FileResponse(open_file, as_attachment=False, filename='', **kwargs)
  758. :class:`FileResponse` is a subclass of :class:`StreamingHttpResponse`
  759. optimized for binary files. It uses `wsgi.file_wrapper`_ if provided by the
  760. wsgi server, otherwise it streams the file out in small chunks.
  761. If ``as_attachment=True``, the ``Content-Disposition`` header is set, which
  762. asks the browser to offer the file to the user as a download.
  763. If ``open_file`` doesn't have a name or if the name of ``open_file`` isn't
  764. appropriate, provide a custom file name using the ``filename`` parameter.
  765. The ``Content-Length``, ``Content-Type``, and ``Content-Disposition``
  766. headers are automatically set when they can be guessed from contents of
  767. ``open_file``.
  768. .. _wsgi.file_wrapper: https://www.python.org/dev/peps/pep-3333/#optional-platform-specific-file-handling
  769. ``FileResponse`` accepts any file-like object with binary content, for example
  770. a file open in binary mode like so::
  771. >>> from django.http import FileResponse
  772. >>> response = FileResponse(open('myfile.png', 'rb'))
  773. The file will be closed automatically, so don't open it with a context manager.
  774. Methods
  775. -------
  776. .. method:: FileResponse.set_headers(open_file)
  777. This method is automatically called during the response initialization and
  778. set various headers (``Content-Length``, ``Content-Type``, and
  779. ``Content-Disposition``) depending on ``open_file``.