request-response.txt 31 KB

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