request-response.txt 40 KB

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