request-response.txt 39 KB

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