request-response.txt 39 KB

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