request-response.txt 31 KB

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