request-response.txt 39 KB

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