request-response.txt 36 KB

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