request-response.txt 39 KB

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