request-response.txt 38 KB

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