request-response.txt 40 KB

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