request-response.txt 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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.
  15. HttpRequest objects
  16. ===================
  17. .. class:: HttpRequest
  18. .. _httprequest-attributes:
  19. Attributes
  20. ----------
  21. All attributes should be considered read-only, unless stated otherwise below.
  22. ``session`` is a notable exception.
  23. .. attribute:: HttpRequest.body
  24. .. versionchanged:: 1.4
  25. Before Django 1.4, ``HttpRequest.body`` was named
  26. ``HttpRequest.raw_post_data``.
  27. The raw HTTP request body as a byte string. This is useful for processing
  28. data in different ways than conventional HTML forms: binary images,
  29. XML payload etc. For processing conventional form data, use ``HttpRequest.POST``.
  30. .. versionadded:: 1.3
  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. See the
  66. :class:`QueryDict` documentation below.
  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. A ``django.contrib.auth.models.User`` object representing the currently
  119. logged-in user. If the user isn't currently logged in, ``user`` will be set
  120. to an instance of ``django.contrib.auth.models.AnonymousUser``. You
  121. can tell them apart with ``is_authenticated()``, like so::
  122. if request.user.is_authenticated():
  123. # Do something for logged-in users.
  124. else:
  125. # Do something for anonymous users.
  126. ``user`` is only available if your Django installation has the
  127. ``AuthenticationMiddleware`` activated. For more, see
  128. :doc:`/topics/auth`.
  129. .. attribute:: HttpRequest.session
  130. A readable-and-writable, dictionary-like object that represents the current
  131. session. This is only available if your Django installation has session
  132. support activated. See the :doc:`session documentation
  133. </topics/http/sessions>` for full details.
  134. .. attribute:: HttpRequest.urlconf
  135. Not defined by Django itself, but will be read if other code (e.g., a custom
  136. middleware class) sets it. When present, this will be used as the root
  137. URLconf for the current request, overriding the :setting:`ROOT_URLCONF`
  138. setting. See :ref:`how-django-processes-a-request` for details.
  139. Methods
  140. -------
  141. .. method:: HttpRequest.get_host()
  142. Returns the originating host of the request using information from the
  143. ``HTTP_X_FORWARDED_HOST`` (if :setting:`USE_X_FORWARDED_HOST` is enabled)
  144. and ``HTTP_HOST`` headers, in that order. If they don't provide a value,
  145. the method uses a combination of ``SERVER_NAME`` and ``SERVER_PORT`` as
  146. detailed in :pep:`3333`.
  147. Example: ``"127.0.0.1:8000"``
  148. .. note:: The :meth:`~HttpRequest.get_host()` method fails when the host is
  149. behind multiple proxies. One solution is to use middleware to rewrite
  150. the proxy headers, as in the following example::
  151. class MultipleProxyMiddleware(object):
  152. FORWARDED_FOR_FIELDS = [
  153. 'HTTP_X_FORWARDED_FOR',
  154. 'HTTP_X_FORWARDED_HOST',
  155. 'HTTP_X_FORWARDED_SERVER',
  156. ]
  157. def process_request(self, request):
  158. """
  159. Rewrites the proxy headers so that only the most
  160. recent proxy is used.
  161. """
  162. for field in self.FORWARDED_FOR_FIELDS:
  163. if field in request.META:
  164. if ',' in request.META[field]:
  165. parts = request.META[field].split(',')
  166. request.META[field] = parts[-1].strip()
  167. This middleware should be positioned before any other middleware that
  168. relies on the value of :meth:`~HttpRequest.get_host()` -- for instance,
  169. :class:`~django.middleware.common.CommonMiddleware` or
  170. :class:`~django.middleware.csrf.CsrfViewMiddleware`.
  171. .. method:: HttpRequest.get_full_path()
  172. Returns the ``path``, plus an appended query string, if applicable.
  173. Example: ``"/music/bands/the_beatles/?print=true"``
  174. .. method:: HttpRequest.build_absolute_uri(location)
  175. Returns the absolute URI form of ``location``. If no location is provided,
  176. the location will be set to ``request.get_full_path()``.
  177. If the location is already an absolute URI, it will not be altered.
  178. Otherwise the absolute URI is built using the server variables available in
  179. this request.
  180. Example: ``"http://example.com/music/bands/the_beatles/?print=true"``
  181. .. method:: HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
  182. .. versionadded:: 1.4
  183. Returns a cookie value for a signed cookie, or raises a
  184. :class:`~django.core.signing.BadSignature` exception if the signature is
  185. no longer valid. If you provide the ``default`` argument the exception
  186. will be suppressed and that default value will be returned instead.
  187. The optional ``salt`` argument can be used to provide extra protection
  188. against brute force attacks on your secret key. If supplied, the
  189. ``max_age`` argument will be checked against the signed timestamp
  190. attached to the cookie value to ensure the cookie is not older than
  191. ``max_age`` seconds.
  192. For example::
  193. >>> request.get_signed_cookie('name')
  194. 'Tony'
  195. >>> request.get_signed_cookie('name', salt='name-salt')
  196. 'Tony' # assuming cookie was set using the same salt
  197. >>> request.get_signed_cookie('non-existing-cookie')
  198. ...
  199. KeyError: 'non-existing-cookie'
  200. >>> request.get_signed_cookie('non-existing-cookie', False)
  201. False
  202. >>> request.get_signed_cookie('cookie-that-was-tampered-with')
  203. ...
  204. BadSignature: ...
  205. >>> request.get_signed_cookie('name', max_age=60)
  206. ...
  207. SignatureExpired: Signature age 1677.3839159 > 60 seconds
  208. >>> request.get_signed_cookie('name', False, max_age=60)
  209. False
  210. See :doc:`cryptographic signing </topics/signing>` for more information.
  211. .. method:: HttpRequest.is_secure()
  212. Returns ``True`` if the request is secure; that is, if it was made with
  213. HTTPS.
  214. .. method:: HttpRequest.is_ajax()
  215. Returns ``True`` if the request was made via an ``XMLHttpRequest``, by
  216. checking the ``HTTP_X_REQUESTED_WITH`` header for the string
  217. ``'XMLHttpRequest'``. Most modern JavaScript libraries send this header.
  218. If you write your own XMLHttpRequest call (on the browser side), you'll
  219. have to set this header manually if you want ``is_ajax()`` to work.
  220. .. method:: HttpRequest.read(size=None)
  221. .. method:: HttpRequest.readline()
  222. .. method:: HttpRequest.readlines()
  223. .. method:: HttpRequest.xreadlines()
  224. .. method:: HttpRequest.__iter__()
  225. .. versionadded:: 1.3
  226. Methods implementing a file-like interface for reading from an
  227. HttpRequest instance. This makes it possible to consume an incoming
  228. request in a streaming fashion. A common use-case would be to process a
  229. big XML payload with iterative parser without constructing a whole
  230. XML tree in memory.
  231. Given this standard interface, an HttpRequest instance can be
  232. passed directly to an XML parser such as ElementTree::
  233. import xml.etree.ElementTree as ET
  234. for element in ET.iterparse(request):
  235. process(element)
  236. UploadedFile objects
  237. ====================
  238. .. class:: UploadedFile
  239. Attributes
  240. ----------
  241. .. attribute:: UploadedFile.name
  242. The name of the uploaded file.
  243. .. attribute:: UploadedFile.size
  244. The size, in bytes, of the uploaded file.
  245. Methods
  246. ----------
  247. .. method:: UploadedFile.chunks(chunk_size=None)
  248. Returns a generator that yields sequential chunks of data.
  249. .. method:: UploadedFile.read(num_bytes=None)
  250. Read a number of bytes from the file.
  251. QueryDict objects
  252. =================
  253. .. class:: QueryDict
  254. In an :class:`HttpRequest` object, the ``GET`` and ``POST`` attributes are instances
  255. of ``django.http.QueryDict``. :class:`QueryDict` is a dictionary-like
  256. class customized to deal with multiple values for the same key. This is
  257. necessary because some HTML form elements, notably
  258. ``<select multiple="multiple">``, pass multiple values for the same key.
  259. ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them.
  260. That means you can't change attributes of ``request.POST`` and ``request.GET``
  261. directly.
  262. Methods
  263. -------
  264. :class:`QueryDict` implements all the standard dictionary methods, because it's
  265. a subclass of dictionary. Exceptions are outlined here:
  266. .. method:: QueryDict.__getitem__(key)
  267. Returns the value for the given key. If the key has more than one value,
  268. ``__getitem__()`` returns the last value. Raises
  269. ``django.utils.datastructures.MultiValueDictKeyError`` if the key does not
  270. exist. (This is a subclass of Python's standard ``KeyError``, so you can
  271. stick to catching ``KeyError``.)
  272. .. method:: QueryDict.__setitem__(key, value)
  273. Sets the given key to ``[value]`` (a Python list whose single element is
  274. ``value``). Note that this, as other dictionary functions that have side
  275. effects, can only be called on a mutable ``QueryDict`` (one that was created
  276. via ``copy()``).
  277. .. method:: QueryDict.__contains__(key)
  278. Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
  279. in request.GET``.
  280. .. method:: QueryDict.get(key, default)
  281. Uses the same logic as ``__getitem__()`` above, with a hook for returning a
  282. default value if the key doesn't exist.
  283. .. method:: QueryDict.setdefault(key, default)
  284. Just like the standard dictionary ``setdefault()`` method, except it uses
  285. ``__setitem__()`` internally.
  286. .. method:: QueryDict.update(other_dict)
  287. Takes either a ``QueryDict`` or standard dictionary. Just like the standard
  288. dictionary ``update()`` method, except it *appends* to the current
  289. dictionary items rather than replacing them. For example::
  290. >>> q = QueryDict('a=1')
  291. >>> q = q.copy() # to make it mutable
  292. >>> q.update({'a': '2'})
  293. >>> q.getlist('a')
  294. [u'1', u'2']
  295. >>> q['a'] # returns the last
  296. [u'2']
  297. .. method:: QueryDict.items()
  298. Just like the standard dictionary ``items()`` method, except this uses the
  299. same last-value logic as ``__getitem__()``. For example::
  300. >>> q = QueryDict('a=1&a=2&a=3')
  301. >>> q.items()
  302. [(u'a', u'3')]
  303. .. method:: QueryDict.iteritems()
  304. Just like the standard dictionary ``iteritems()`` method. Like
  305. :meth:`QueryDict.items()` this uses the same last-value logic as
  306. :meth:`QueryDict.__getitem__()`.
  307. .. method:: QueryDict.iterlists()
  308. Like :meth:`QueryDict.iteritems()` except it includes all values, as a list,
  309. for each member of the dictionary.
  310. .. method:: QueryDict.values()
  311. Just like the standard dictionary ``values()`` method, except this uses the
  312. same last-value logic as ``__getitem__()``. For example::
  313. >>> q = QueryDict('a=1&a=2&a=3')
  314. >>> q.values()
  315. [u'3']
  316. .. method:: QueryDict.itervalues()
  317. Just like :meth:`QueryDict.values()`, except an iterator.
  318. In addition, ``QueryDict`` has the following methods:
  319. .. method:: QueryDict.copy()
  320. Returns a copy of the object, using ``copy.deepcopy()`` from the Python
  321. standard library. The copy will be mutable -- that is, you can change its
  322. values.
  323. .. method:: QueryDict.getlist(key, default)
  324. Returns the data with the requested key, as a Python list. Returns an
  325. empty list if the key doesn't exist and no default value was provided.
  326. It's guaranteed to return a list of some sort unless the default value
  327. was no list.
  328. .. versionchanged:: 1.4
  329. The ``default`` parameter was added.
  330. .. method:: QueryDict.setlist(key, list_)
  331. Sets the given key to ``list_`` (unlike ``__setitem__()``).
  332. .. method:: QueryDict.appendlist(key, item)
  333. Appends an item to the internal list associated with key.
  334. .. method:: QueryDict.setlistdefault(key, default_list)
  335. Just like ``setdefault``, except it takes a list of values instead of a
  336. single value.
  337. .. method:: QueryDict.lists()
  338. Like :meth:`items()`, except it includes all values, as a list, for each
  339. member of the dictionary. For example::
  340. >>> q = QueryDict('a=1&a=2&a=3')
  341. >>> q.lists()
  342. [(u'a', [u'1', u'2', u'3'])]
  343. .. method:: QueryDict.dict()
  344. .. versionadded:: 1.4
  345. Returns ``dict`` representation of ``QueryDict``. For every (key, list)
  346. pair in ``QueryDict``, ``dict`` will have (key, item), where item is one
  347. element of the list, using same logic as :meth:`QueryDict.__getitem__()`::
  348. >>> q = QueryDict('a=1&a=3&a=5')
  349. >>> q.dict()
  350. {u'a': u'5'}
  351. .. method:: QueryDict.urlencode([safe])
  352. Returns a string of the data in query-string format. Example::
  353. >>> q = QueryDict('a=2&b=3&b=5')
  354. >>> q.urlencode()
  355. 'a=2&b=3&b=5'
  356. .. versionchanged:: 1.3
  357. The ``safe`` parameter was added.
  358. Optionally, urlencode can be passed characters which
  359. do not require encoding. For example::
  360. >>> q = QueryDict('', mutable=True)
  361. >>> q['next'] = '/a&b/'
  362. >>> q.urlencode(safe='/')
  363. 'next=/a%26b/'
  364. HttpResponse objects
  365. ====================
  366. .. class:: HttpResponse
  367. In contrast to :class:`HttpRequest` objects, which are created automatically by
  368. Django, :class:`HttpResponse` objects are your responsibility. Each view you
  369. write is responsible for instantiating, populating and returning an
  370. :class:`HttpResponse`.
  371. The :class:`HttpResponse` class lives in the :mod:`django.http` module.
  372. Usage
  373. -----
  374. Passing strings
  375. ~~~~~~~~~~~~~~~
  376. Typical usage is to pass the contents of the page, as a string, to the
  377. :class:`HttpResponse` constructor::
  378. >>> from django.http import HttpResponse
  379. >>> response = HttpResponse("Here's the text of the Web page.")
  380. >>> response = HttpResponse("Text only, please.", content_type="text/plain")
  381. But if you want to add content incrementally, you can use ``response`` as a
  382. file-like object::
  383. >>> response = HttpResponse()
  384. >>> response.write("<p>Here's the text of the Web page.</p>")
  385. >>> response.write("<p>Here's another paragraph.</p>")
  386. Passing iterators
  387. ~~~~~~~~~~~~~~~~~
  388. Finally, you can pass ``HttpResponse`` an iterator rather than passing it
  389. hard-coded strings. If you use this technique, follow these guidelines:
  390. * The iterator should return strings.
  391. * If an :class:`HttpResponse` has been initialized with an iterator as its
  392. content, you can't use the :class:`HttpResponse` instance as a file-like
  393. object. Doing so will raise ``Exception``.
  394. Setting headers
  395. ~~~~~~~~~~~~~~~
  396. To set or remove a header in your response, treat it like a dictionary::
  397. >>> response = HttpResponse()
  398. >>> response['Cache-Control'] = 'no-cache'
  399. >>> del response['Cache-Control']
  400. Note that unlike a dictionary, ``del`` doesn't raise ``KeyError`` if the header
  401. doesn't exist.
  402. HTTP headers cannot contain newlines. An attempt to set a header containing a
  403. newline character (CR or LF) will raise ``BadHeaderError``
  404. Telling the browser to treat the response as a file attachment
  405. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  406. To tell the browser to treat the response as a file attachment, use the
  407. ``content_type`` argument and set the ``Content-Disposition`` header. For example,
  408. this is how you might return a Microsoft Excel spreadsheet::
  409. >>> response = HttpResponse(my_data, content_type='application/vnd.ms-excel')
  410. >>> response['Content-Disposition'] = 'attachment; filename=foo.xls'
  411. There's nothing Django-specific about the ``Content-Disposition`` header, but
  412. it's easy to forget the syntax, so we've included it here.
  413. Attributes
  414. ----------
  415. .. attribute:: HttpResponse.content
  416. A string representing the content, encoded from a Unicode
  417. object if necessary.
  418. .. attribute:: HttpResponse.status_code
  419. The `HTTP Status code`_ for the response.
  420. Methods
  421. -------
  422. .. method:: HttpResponse.__init__(content='', content_type=None, status=200)
  423. Instantiates an ``HttpResponse`` object with the given page content and
  424. content type.
  425. ``content`` should be an iterator or a string. If it's an
  426. iterator, it should return strings, and those strings will be
  427. joined together to form the content of the response. If it is not
  428. an iterator or a string, it will be converted to a string when
  429. accessed.
  430. ``content_type`` is the MIME type optionally completed by a character set
  431. encoding and is used to fill the HTTP ``Content-Type`` header. If not
  432. specified, it is formed by the :setting:`DEFAULT_CONTENT_TYPE` and
  433. :setting:`DEFAULT_CHARSET` settings, by default: "`text/html; charset=utf-8`".
  434. Historically, this parameter was called ``mimetype`` (now deprecated).
  435. ``status`` is the `HTTP Status code`_ for the response.
  436. .. method:: HttpResponse.__setitem__(header, value)
  437. Sets the given header name to the given value. Both ``header`` and
  438. ``value`` should be strings.
  439. .. method:: HttpResponse.__delitem__(header)
  440. Deletes the header with the given name. Fails silently if the header
  441. doesn't exist. Case-insensitive.
  442. .. method:: HttpResponse.__getitem__(header)
  443. Returns the value for the given header name. Case-insensitive.
  444. .. method:: HttpResponse.has_header(header)
  445. Returns ``True`` or ``False`` based on a case-insensitive check for a
  446. header with the given name.
  447. .. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=True)
  448. .. versionchanged:: 1.3
  449. The possibility of specifying a ``datetime.datetime`` object in
  450. ``expires``, and the auto-calculation of ``max_age`` in such case
  451. was added. The ``httponly`` argument was also added.
  452. .. versionchanged:: 1.4
  453. The default value for httponly was changed from ``False`` to ``True``.
  454. Sets a cookie. The parameters are the same as in the :class:`Cookie.Morsel`
  455. object in the Python standard library.
  456. * ``max_age`` should be a number of seconds, or ``None`` (default) if
  457. the cookie should last only as long as the client's browser session.
  458. If ``expires`` is not specified, it will be calculated.
  459. * ``expires`` should either be a string in the format
  460. ``"Wdy, DD-Mon-YY HH:MM:SS GMT"`` or a ``datetime.datetime`` object
  461. in UTC. If ``expires`` is a ``datetime`` object, the ``max_age``
  462. will be calculated.
  463. * Use ``domain`` if you want to set a cross-domain cookie. For example,
  464. ``domain=".lawrence.com"`` will set a cookie that is readable by
  465. the domains www.lawrence.com, blogs.lawrence.com and
  466. calendars.lawrence.com. Otherwise, a cookie will only be readable by
  467. the domain that set it.
  468. * Use ``httponly=True`` if you want to prevent client-side
  469. JavaScript from having access to the cookie.
  470. HTTPOnly_ is a flag included in a Set-Cookie HTTP response
  471. header. It is not part of the :rfc:`2109` standard for cookies,
  472. and it isn't honored consistently by all browsers. However,
  473. when it is honored, it can be a useful way to mitigate the
  474. risk of client side script accessing the protected cookie
  475. data.
  476. .. _HTTPOnly: https://www.owasp.org/index.php/HTTPOnly
  477. .. method:: HttpResponse.set_signed_cookie(key, value='', salt='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=True)
  478. .. versionadded:: 1.4
  479. Like :meth:`~HttpResponse.set_cookie()`, but
  480. :doc:`cryptographic signing </topics/signing>` the cookie before setting
  481. it. Use in conjunction with :meth:`HttpRequest.get_signed_cookie`.
  482. You can use the optional ``salt`` argument for added key strength, but
  483. you will need to remember to pass it to the corresponding
  484. :meth:`HttpRequest.get_signed_cookie` call.
  485. .. method:: HttpResponse.delete_cookie(key, path='/', domain=None)
  486. Deletes the cookie with the given key. Fails silently if the key doesn't
  487. exist.
  488. Due to the way cookies work, ``path`` and ``domain`` should be the same
  489. values you used in ``set_cookie()`` -- otherwise the cookie may not be
  490. deleted.
  491. .. method:: HttpResponse.write(content)
  492. This method makes an :class:`HttpResponse` instance a file-like object.
  493. .. method:: HttpResponse.flush()
  494. This method makes an :class:`HttpResponse` instance a file-like object.
  495. .. method:: HttpResponse.tell()
  496. This method makes an :class:`HttpResponse` instance a file-like object.
  497. .. _HTTP Status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
  498. .. _ref-httpresponse-subclasses:
  499. HttpResponse subclasses
  500. -----------------------
  501. Django includes a number of ``HttpResponse`` subclasses that handle different
  502. types of HTTP responses. Like ``HttpResponse``, these subclasses live in
  503. :mod:`django.http`.
  504. .. class:: HttpResponseRedirect
  505. The constructor takes a single argument -- the path to redirect to. This
  506. can be a fully qualified URL (e.g. ``'http://www.yahoo.com/search/'``) or
  507. an absolute path with no domain (e.g. ``'/search/'``). Note that this
  508. returns an HTTP status code 302.
  509. .. class:: HttpResponsePermanentRedirect
  510. Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
  511. (HTTP status code 301) instead of a "found" redirect (status code 302).
  512. .. class:: HttpResponseNotModified
  513. The constructor doesn't take any arguments. Use this to designate that a
  514. page hasn't been modified since the user's last request (status code 304).
  515. .. class:: HttpResponseBadRequest
  516. Acts just like :class:`HttpResponse` but uses a 400 status code.
  517. .. class:: HttpResponseNotFound
  518. Acts just like :class:`HttpResponse` but uses a 404 status code.
  519. .. class:: HttpResponseForbidden
  520. Acts just like :class:`HttpResponse` but uses a 403 status code.
  521. .. class:: HttpResponseNotAllowed
  522. Like :class:`HttpResponse`, but uses a 405 status code. Takes a single,
  523. required argument: a list of permitted methods (e.g. ``['GET', 'POST']``).
  524. .. class:: HttpResponseGone
  525. Acts just like :class:`HttpResponse` but uses a 410 status code.
  526. .. class:: HttpResponseServerError
  527. Acts just like :class:`HttpResponse` but uses a 500 status code.
  528. .. note::
  529. If a custom subclass of :class:`HttpResponse` implements a ``render``
  530. method, Django will treat it as emulating a
  531. :class:`~django.template.response.SimpleTemplateResponse`, and the
  532. ``render`` method must itself return a valid response object.