request-response.txt 27 KB

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