request-response.txt 40 KB

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