request-response.txt 35 KB

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