request-response.txt 35 KB

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