request-response.txt 39 KB

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