request-response.txt 37 KB

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