request-response.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. .. _ref-request-response:
  2. ============================
  3. Request and response objects
  4. ============================
  5. .. module:: django.http
  6. :synopsis: Classes dealing with HTTP requests and responses.
  7. Quick overview
  8. ==============
  9. Django uses request and response objects to pass state through the system.
  10. When a page is requested, Django creates an :class:`HttpRequest` object that
  11. contains metadata about the request. Then Django loads the appropriate view,
  12. passing the :class:`HttpRequest` as the first argument to the view function.
  13. Each view is responsible for returning an :class:`HttpResponse` object.
  14. This document explains the APIs for :class:`HttpRequest` and
  15. :class:`HttpResponse` objects.
  16. HttpRequest objects
  17. ===================
  18. .. class:: HttpRequest
  19. Attributes
  20. ----------
  21. All attributes except ``session`` should be considered read-only.
  22. .. attribute:: HttpRequest.path
  23. A string representing the full path to the requested page, not including
  24. the domain.
  25. Example: ``"/music/bands/the_beatles/"``
  26. .. attribute:: HttpRequest.method
  27. A string representing the HTTP method used in the request. This is
  28. guaranteed to be uppercase. Example::
  29. if request.method == 'GET':
  30. do_something()
  31. elif request.method == 'POST':
  32. do_something_else()
  33. .. attribute:: HttpRequest.encoding
  34. .. versionadded:: 1.0
  35. A string representing the current encoding used to decode form submission
  36. data (or ``None``, which means the ``DEFAULT_CHARSET`` setting is used).
  37. You can write to this attribute to change the encoding used when accessing
  38. the form data. Any subsequent attribute accesses (such as reading from
  39. ``GET`` or ``POST``) will use the new ``encoding`` value. Useful if you
  40. know the form data is not in the ``DEFAULT_CHARSET`` encoding.
  41. .. attribute:: HttpRequest.GET
  42. A dictionary-like object containing all given HTTP GET parameters. See the
  43. ``QueryDict`` documentation below.
  44. .. attribute:: HttpRequest.POST
  45. A dictionary-like object containing all given HTTP POST parameters. See the
  46. ``QueryDict`` documentation below.
  47. It's possible that a request can come in via POST with an empty ``POST``
  48. dictionary -- if, say, a form is requested via the POST HTTP method but
  49. does not include form data. Therefore, you shouldn't use ``if request.POST``
  50. to check for use of the POST method; instead, use ``if request.method ==
  51. "POST"`` (see above).
  52. Note: ``POST`` does *not* include file-upload information. See ``FILES``.
  53. .. attribute:: HttpRequest.REQUEST
  54. For convenience, a dictionary-like object that searches ``POST`` first,
  55. then ``GET``. Inspired by PHP's ``$_REQUEST``.
  56. For example, if ``GET = {"name": "john"}`` and ``POST = {"age": '34'}``,
  57. ``REQUEST["name"]`` would be ``"john"``, and ``REQUEST["age"]`` would be
  58. ``"34"``.
  59. It's strongly suggested that you use ``GET`` and ``POST`` instead of
  60. ``REQUEST``, because the former are more explicit.
  61. .. attribute:: HttpRequest.COOKIES
  62. A standard Python dictionary containing all cookies. Keys and values are
  63. strings.
  64. .. attribute:: HttpRequest.FILES
  65. A dictionary-like object containing all uploaded files. Each key in
  66. ``FILES`` is the ``name`` from the ``<input type="file" name="" />``. Each
  67. value in ``FILES`` is an ``UploadedFile`` object containing the following
  68. attributes:
  69. * ``read(num_bytes=None)`` -- Read a number of bytes from the file.
  70. * ``name`` -- The name of the uploaded file.
  71. * ``size`` -- The size, in bytes, of the uploaded file.
  72. * ``chunks(chunk_size=None)`` -- A generator that yields sequential
  73. chunks of data.
  74. See :ref:`topics-files` for more information.
  75. Note that ``FILES`` will only contain data if the request method was POST
  76. and the ``<form>`` that posted to the request had
  77. ``enctype="multipart/form-data"``. Otherwise, ``FILES`` will be a blank
  78. dictionary-like object.
  79. .. versionchanged:: 1.0
  80. In previous versions of Django, ``request.FILES`` contained simple ``dict``
  81. objects representing uploaded files. This is no longer true -- files are
  82. represented by ``UploadedFile`` objects as described below.
  83. These ``UploadedFile`` objects will emulate the old-style ``dict``
  84. interface, but this is deprecated and will be removed in the next release of
  85. Django.
  86. .. attribute:: HttpRequest.META
  87. A standard Python dictionary containing all available HTTP headers.
  88. Available headers depend on the client and server, but here are some
  89. examples:
  90. * ``CONTENT_LENGTH``
  91. * ``CONTENT_TYPE``
  92. * ``HTTP_ACCEPT_ENCODING``
  93. * ``HTTP_ACCEPT_LANGUAGE``
  94. * ``HTTP_HOST`` -- The HTTP Host header sent by the client.
  95. * ``HTTP_REFERER`` -- The referring page, if any.
  96. * ``HTTP_USER_AGENT`` -- The client's user-agent string.
  97. * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
  98. * ``REMOTE_ADDR`` -- The IP address of the client.
  99. * ``REMOTE_HOST`` -- The hostname of the client.
  100. * ``REMOTE_USER`` -- The user authenticated by the web server, if any.
  101. * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
  102. * ``SERVER_NAME`` -- The hostname of the server.
  103. * ``SERVER_PORT`` -- The port of the server.
  104. With the exception of ``CONTENT_LENGTH`` and ``CONTENT_TYPE``, as given
  105. above, any HTTP headers in the request are converted to ``META`` keys by
  106. converting all characters to uppercase, replacing any hyphens with
  107. underscores and adding an ``HTTP_`` prefix to the name. So, for example, a
  108. header called ``X-Bender`` would be mapped to the ``META`` key
  109. ``HTTP_X_BENDER``.
  110. .. attribute:: HttpRequest.user
  111. A ``django.contrib.auth.models.User`` object representing the currently
  112. logged-in user. If the user isn't currently logged in, ``user`` will be set
  113. to an instance of ``django.contrib.auth.models.AnonymousUser``. You
  114. can tell them apart with ``is_authenticated()``, like so::
  115. if request.user.is_authenticated():
  116. # Do something for logged-in users.
  117. else:
  118. # Do something for anonymous users.
  119. ``user`` is only available if your Django installation has the
  120. ``AuthenticationMiddleware`` activated. For more, see
  121. :ref:`topics-auth`.
  122. .. attribute:: HttpRequest.session
  123. A readable-and-writable, dictionary-like object that represents the current
  124. session. This is only available if your Django installation has session
  125. support activated. See the :ref:`session documentation
  126. <topics-http-sessions>` for full details.
  127. .. attribute:: HttpRequest.raw_post_data
  128. The raw HTTP POST data. This is only useful for advanced processing. Use
  129. ``POST`` instead.
  130. .. attribute:: HttpRequest.urlconf
  131. Not defined by Django itself, but will be read if other code (e.g., a custom
  132. middleware class) sets it. When present, this will be used as the root
  133. URLconf for the current request, overriding the ``ROOT_URLCONF`` setting.
  134. See :ref:`how-django-processes-a-request` for details.
  135. Methods
  136. -------
  137. .. method:: HttpRequest.get_host()
  138. .. versionadded:: 1.0
  139. Returns the originating host of the request using information from the
  140. ``HTTP_X_FORWARDED_HOST`` and ``HTTP_HOST`` headers (in that order). If
  141. they don't provide a value, the method uses a combination of
  142. ``SERVER_NAME`` and ``SERVER_PORT`` as detailed in `PEP 333`_.
  143. .. _PEP 333: http://www.python.org/dev/peps/pep-0333/
  144. Example: ``"127.0.0.1:8000"``
  145. .. method:: HttpRequest.get_full_path()
  146. Returns the ``path``, plus an appended query string, if applicable.
  147. Example: ``"/music/bands/the_beatles/?print=true"``
  148. .. method:: HttpRequest.build_absolute_uri(location)
  149. .. versionadded:: 1.0
  150. Returns the absolute URI form of ``location``. If no location is provided,
  151. the location will be set to ``request.get_full_path()``.
  152. If the location is already an absolute URI, it will not be altered.
  153. Otherwise the absolute URI is built using the server variables available in
  154. this request.
  155. Example: ``"http://example.com/music/bands/the_beatles/?print=true"``
  156. .. method:: HttpRequest.is_secure()
  157. Returns ``True`` if the request is secure; that is, if it was made with
  158. HTTPS.
  159. .. method:: HttpRequest.is_ajax()
  160. .. versionadded:: 1.0
  161. Returns ``True`` if the request was made via an ``XMLHttpRequest``, by
  162. checking the ``HTTP_X_REQUESTED_WITH`` header for the string
  163. ``'XMLHttpRequest'``. Most modern JavaScript libraries send this header.
  164. If you write your own XMLHttpRequest call (on the browser side), you'll
  165. have to set this header manually if you want ``is_ajax()`` to work.
  166. QueryDict objects
  167. -----------------
  168. .. class:: QueryDict
  169. In an :class:`HttpRequest` object, the ``GET`` and ``POST`` attributes are instances
  170. of ``django.http.QueryDict``. :class:`QueryDict` is a dictionary-like
  171. class customized to deal with multiple values for the same key. This is
  172. necessary because some HTML form elements, notably
  173. ``<select multiple="multiple">``, pass multiple values for the same key.
  174. ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them.
  175. That means you can't change attributes of ``request.POST`` and ``request.GET``
  176. directly.
  177. Methods
  178. -------
  179. :class:`QueryDict` implements all the standard dictionary methods, because it's
  180. a subclass of dictionary. Exceptions are outlined here:
  181. .. method:: QueryDict.__getitem__(key)
  182. Returns the value for the given key. If the key has more than one value,
  183. ``__getitem__()`` returns the last value. Raises
  184. ``django.utils.datastructures.MultiValueDictKeyError`` if the key does not
  185. exist. (This is a subclass of Python's standard ``KeyError``, so you can
  186. stick to catching ``KeyError``.)
  187. .. method:: QueryDict.__setitem__(key, value)
  188. Sets the given key to ``[value]`` (a Python list whose single element is
  189. ``value``). Note that this, as other dictionary functions that have side
  190. effects, can only be called on a mutable ``QueryDict`` (one that was created
  191. via ``copy()``).
  192. .. method:: QueryDict.__contains__(key)
  193. Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
  194. in request.GET``.
  195. .. method:: QueryDict.get(key, default)
  196. Uses the same logic as ``__getitem__()`` above, with a hook for returning a
  197. default value if the key doesn't exist.
  198. .. method:: QueryDict.setdefault(key, default)
  199. Just like the standard dictionary ``setdefault()`` method, except it uses
  200. ``__setitem__`` internally.
  201. .. method:: QueryDict.update(other_dict)
  202. Takes either a ``QueryDict`` or standard dictionary. Just like the standard
  203. dictionary ``update()`` method, except it *appends* to the current
  204. dictionary items rather than replacing them. For example::
  205. >>> q = QueryDict('a=1')
  206. >>> q = q.copy() # to make it mutable
  207. >>> q.update({'a': '2'})
  208. >>> q.getlist('a')
  209. ['1', '2']
  210. >>> q['a'] # returns the last
  211. ['2']
  212. .. method:: QueryDict.items()
  213. Just like the standard dictionary ``items()`` method, except this uses the
  214. same last-value logic as ``__getitem()__``. For example::
  215. >>> q = QueryDict('a=1&a=2&a=3')
  216. >>> q.items()
  217. [('a', '3')]
  218. .. method:: QueryDict.iteritems()
  219. Just like the standard dictionary ``iteritems()`` method. Like
  220. :meth:`QueryDict.items()` this uses the same last-value logic as
  221. :meth:`QueryDict.__getitem()__`.
  222. .. method:: QueryDict.iterlists()
  223. Like :meth:`QueryDict.iteritems()` except it includes all values, as a list,
  224. for each member of the dictionary.
  225. .. method:: QueryDict.values()
  226. Just like the standard dictionary ``values()`` method, except this uses the
  227. same last-value logic as ``__getitem()__``. For example::
  228. >>> q = QueryDict('a=1&a=2&a=3')
  229. >>> q.values()
  230. ['3']
  231. .. method:: QueryDict.itervalues()
  232. Just like :meth:`QueryDict.values()`, except an iterator.
  233. In addition, ``QueryDict`` has the following methods:
  234. .. method:: QueryDict.copy()
  235. Returns a copy of the object, using ``copy.deepcopy()`` from the Python
  236. standard library. The copy will be mutable -- that is, you can change its
  237. values.
  238. .. method:: QueryDict.getlist(key)
  239. Returns the data with the requested key, as a Python list. Returns an
  240. empty list if the key doesn't exist. It's guaranteed to return a list of
  241. some sort.
  242. .. method:: QueryDict.setlist(key, list_)
  243. Sets the given key to ``list_`` (unlike ``__setitem__()``).
  244. .. method:: QueryDict.appendlist(key, item)
  245. Appends an item to the internal list associated with key.
  246. .. method:: QueryDict.setlistdefault(key, default_list)
  247. Just like ``setdefault``, except it takes a list of values instead of a
  248. single value.
  249. .. method:: QueryDict.lists()
  250. Like :meth:`items()`, except it includes all values, as a list, for each
  251. member of the dictionary. For example::
  252. >>> q = QueryDict('a=1&a=2&a=3')
  253. >>> q.lists()
  254. [('a', ['1', '2', '3'])]
  255. .. method:: QueryDict.urlencode()
  256. Returns a string of the data in query-string format.
  257. Example: ``"a=2&b=3&b=5"``.
  258. HttpResponse objects
  259. ====================
  260. .. class:: HttpResponse
  261. In contrast to :class:`HttpRequest` objects, which are created automatically by
  262. Django, :class:`HttpResponse` objects are your responsibility. Each view you
  263. write is responsible for instantiating, populating and returning an
  264. :class:`HttpResponse`.
  265. The :class:`HttpResponse` class lives in the ``django.http`` module.
  266. Usage
  267. -----
  268. Passing strings
  269. ~~~~~~~~~~~~~~~
  270. Typical usage is to pass the contents of the page, as a string, to the
  271. :class:`HttpResponse` constructor::
  272. >>> response = HttpResponse("Here's the text of the Web page.")
  273. >>> response = HttpResponse("Text only, please.", mimetype="text/plain")
  274. But if you want to add content incrementally, you can use ``response`` as a
  275. file-like object::
  276. >>> response = HttpResponse()
  277. >>> response.write("<p>Here's the text of the Web page.</p>")
  278. >>> response.write("<p>Here's another paragraph.</p>")
  279. You can add and delete headers using dictionary syntax::
  280. >>> response = HttpResponse()
  281. >>> response['X-DJANGO'] = "It's the best."
  282. >>> del response['X-PHP']
  283. >>> response['X-DJANGO']
  284. "It's the best."
  285. Note that ``del`` doesn't raise ``KeyError`` if the header doesn't exist.
  286. Passing iterators
  287. ~~~~~~~~~~~~~~~~~
  288. Finally, you can pass ``HttpResponse`` an iterator rather than passing it
  289. hard-coded strings. If you use this technique, follow these guidelines:
  290. * The iterator should return strings.
  291. * If an :class:`HttpResponse` has been initialized with an iterator as its
  292. content, you can't use the class:`HttpResponse` instance as a file-like
  293. object. Doing so will raise ``Exception``.
  294. Setting headers
  295. ~~~~~~~~~~~~~~~
  296. To set a header in your response, just treat it like a dictionary::
  297. >>> response = HttpResponse()
  298. >>> response['Pragma'] = 'no-cache'
  299. .. versionadded:: 1.1
  300. HTTP headers cannot contain newlines. An attempt to set a header containing a
  301. newline character (CR or LF) will raise ``BadHeaderError``
  302. Telling the browser to treat the response as a file attachment
  303. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  304. To tell the browser to treat the response as a file attachment, use the
  305. ``mimetype`` argument and set the ``Content-Disposition`` header. For example,
  306. this is how you might return a Microsoft Excel spreadsheet::
  307. >>> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel')
  308. >>> response['Content-Disposition'] = 'attachment; filename=foo.xls'
  309. There's nothing Django-specific about the ``Content-Disposition`` header, but
  310. it's easy to forget the syntax, so we've included it here.
  311. Attributes
  312. ----------
  313. .. attribute:: HttpResponse.content
  314. A normal Python string representing the content, encoded from a Unicode
  315. object if necessary.
  316. Methods
  317. -------
  318. .. method:: HttpResponse.__init__(content='', mimetype=None, status=200, content_type=DEFAULT_CONTENT_TYPE)
  319. Instantiates an ``HttpResponse`` object with the given page content (a
  320. string) and MIME type. The ``DEFAULT_CONTENT_TYPE`` is ``'text/html'``.
  321. ``content`` can be an iterator or a string. If it's an iterator, it should
  322. return strings, and those strings will be joined together to form the
  323. content of the response.
  324. ``status`` is the `HTTP Status code`_ for the response.
  325. .. versionadded:: 1.0
  326. ``content_type`` is an alias for ``mimetype``. Historically, this parameter
  327. was only called ``mimetype``, but since this is actually the value included
  328. in the HTTP ``Content-Type`` header, it can also include the character set
  329. encoding, which makes it more than just a MIME type specification.
  330. If ``mimetype`` is specified (not ``None``), that value is used.
  331. Otherwise, ``content_type`` is used. If neither is given, the
  332. ``DEFAULT_CONTENT_TYPE`` setting is used.
  333. .. method:: HttpResponse.__setitem__(header, value)
  334. Sets the given header name to the given value. Both ``header`` and
  335. ``value`` should be strings.
  336. .. method:: HttpResponse.__delitem__(header)
  337. Deletes the header with the given name. Fails silently if the header
  338. doesn't exist. Case-sensitive.
  339. .. method:: HttpResponse.__getitem__(header)
  340. Returns the value for the given header name. Case-sensitive.
  341. .. method:: HttpResponse.has_header(header)
  342. Returns ``True`` or ``False`` based on a case-insensitive check for a
  343. header with the given name.
  344. .. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)
  345. Sets a cookie. The parameters are the same as in the `cookie Morsel`_
  346. object in the Python standard library.
  347. * ``max_age`` should be a number of seconds, or ``None`` (default) if
  348. the cookie should last only as long as the client's browser session.
  349. * ``expires`` should be a string in the format
  350. ``"Wdy, DD-Mon-YY HH:MM:SS GMT"``.
  351. * Use ``domain`` if you want to set a cross-domain cookie. For example,
  352. ``domain=".lawrence.com"`` will set a cookie that is readable by
  353. the domains www.lawrence.com, blogs.lawrence.com and
  354. calendars.lawrence.com. Otherwise, a cookie will only be readable by
  355. the domain that set it.
  356. .. _`cookie Morsel`: http://docs.python.org/library/cookie.html#Cookie.Morsel
  357. .. method:: HttpResponse.delete_cookie(key, path='/', domain=None)
  358. Deletes the cookie with the given key. Fails silently if the key doesn't
  359. exist.
  360. Due to the way cookies work, ``path`` and ``domain`` should be the same
  361. values you used in ``set_cookie()`` -- otherwise the cookie may not be
  362. deleted.
  363. .. method:: HttpResponse.write(content)
  364. This method makes an :class:`HttpResponse` instance a file-like object.
  365. .. method:: HttpResponse.flush()
  366. This method makes an :class:`HttpResponse` instance a file-like object.
  367. .. method:: HttpResponse.tell()
  368. This method makes an :class:`HttpResponse` instance a file-like object.
  369. .. _HTTP Status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
  370. .. _ref-httpresponse-subclasses:
  371. HttpResponse subclasses
  372. -----------------------
  373. Django includes a number of ``HttpResponse`` subclasses that handle different
  374. types of HTTP responses. Like ``HttpResponse``, these subclasses live in
  375. :mod:`django.http`.
  376. .. class:: HttpResponseRedirect
  377. The constructor takes a single argument -- the path to redirect to. This
  378. can be a fully qualified URL (e.g. ``'http://www.yahoo.com/search/'``) or an
  379. absolute URL with no domain (e.g. ``'/search/'``). Note that this returns
  380. an HTTP status code 302.
  381. .. class:: HttpResponsePermanentRedirect
  382. Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
  383. (HTTP status code 301) instead of a "found" redirect (status code 302).
  384. .. class:: HttpResponseNotModified
  385. The constructor doesn't take any arguments. Use this to designate that a
  386. page hasn't been modified since the user's last request (status code 304).
  387. .. class:: HttpResponseBadRequest
  388. .. versionadded:: 1.0
  389. Acts just like :class:`HttpResponse` but uses a 400 status code.
  390. .. class:: HttpResponseNotFound
  391. Acts just like :class:`HttpResponse` but uses a 404 status code.
  392. .. class:: HttpResponseForbidden
  393. Acts just like :class:`HttpResponse` but uses a 403 status code.
  394. .. class:: HttpResponseNotAllowed
  395. Like :class:`HttpResponse`, but uses a 405 status code. Takes a single,
  396. required argument: a list of permitted methods (e.g. ``['GET', 'POST']``).
  397. .. class:: HttpResponseGone
  398. Acts just like :class:`HttpResponse` but uses a 410 status code.
  399. .. class:: HttpResponseServerError
  400. Acts just like :class:`HttpResponse` but uses a 500 status code.