parts/django/docs/ref/request-response.txt
changeset 69 c6bca38c1cbf
equal deleted inserted replaced
68:5ff1fc726848 69:c6bca38c1cbf
       
     1 ============================
       
     2 Request and response objects
       
     3 ============================
       
     4 
       
     5 .. module:: django.http
       
     6    :synopsis: Classes dealing with HTTP requests and responses.
       
     7 
       
     8 Quick overview
       
     9 ==============
       
    10 
       
    11 Django uses request and response objects to pass state through the system.
       
    12 
       
    13 When a page is requested, Django creates an :class:`HttpRequest` object that
       
    14 contains metadata about the request. Then Django loads the appropriate view,
       
    15 passing the :class:`HttpRequest` as the first argument to the view function.
       
    16 Each view is responsible for returning an :class:`HttpResponse` object.
       
    17 
       
    18 This document explains the APIs for :class:`HttpRequest` and
       
    19 :class:`HttpResponse` objects.
       
    20 
       
    21 HttpRequest objects
       
    22 ===================
       
    23 
       
    24 .. class:: HttpRequest
       
    25 
       
    26 Attributes
       
    27 ----------
       
    28 
       
    29 All attributes except ``session`` should be considered read-only.
       
    30 
       
    31 .. attribute:: HttpRequest.path
       
    32 
       
    33     A string representing the full path to the requested page, not including
       
    34     the domain.
       
    35 
       
    36     Example: ``"/music/bands/the_beatles/"``
       
    37 
       
    38 .. attribute:: HttpRequest.path_info
       
    39 
       
    40     Under some web server configurations, the portion of the URL after the host
       
    41     name is split up into a script prefix portion and a path info portion
       
    42     (this happens, for example, when using the ``django.root`` option
       
    43     with the :ref:`modpython handler from Apache <howto-deployment-modpython>`).
       
    44     The ``path_info`` attribute always contains the path info portion of the
       
    45     path, no matter what web server is being used. Using this instead of
       
    46     attr:`~HttpRequest.path` can make your code much easier to move between test
       
    47     and deployment servers.
       
    48 
       
    49     For example, if the ``django.root`` for your application is set to 
       
    50     ``"/minfo"``, then ``path`` might be ``"/minfo/music/bands/the_beatles/"``
       
    51     and ``path_info`` would be ``"/music/bands/the_beatles/"``.
       
    52 
       
    53 .. attribute:: HttpRequest.method
       
    54 
       
    55     A string representing the HTTP method used in the request. This is
       
    56     guaranteed to be uppercase. Example::
       
    57 
       
    58         if request.method == 'GET':
       
    59             do_something()
       
    60         elif request.method == 'POST':
       
    61             do_something_else()
       
    62 
       
    63 .. attribute:: HttpRequest.encoding
       
    64 
       
    65     A string representing the current encoding used to decode form submission
       
    66     data (or ``None``, which means the :setting:`DEFAULT_CHARSET` setting is
       
    67     used). You can write to this attribute to change the encoding used when
       
    68     accessing the form data. Any subsequent attribute accesses (such as reading
       
    69     from ``GET`` or ``POST``) will use the new ``encoding`` value.  Useful if
       
    70     you know the form data is not in the :setting:`DEFAULT_CHARSET` encoding.
       
    71 
       
    72 .. attribute:: HttpRequest.GET
       
    73 
       
    74     A dictionary-like object containing all given HTTP GET parameters. See the
       
    75     :class:`QueryDict` documentation below.
       
    76 
       
    77 .. attribute:: HttpRequest.POST
       
    78 
       
    79     A dictionary-like object containing all given HTTP POST parameters. See the
       
    80     :class:`QueryDict` documentation below.
       
    81 
       
    82     It's possible that a request can come in via POST with an empty ``POST``
       
    83     dictionary -- if, say, a form is requested via the POST HTTP method but
       
    84     does not include form data. Therefore, you shouldn't use ``if request.POST``
       
    85     to check for use of the POST method; instead, use ``if request.method ==
       
    86     "POST"`` (see above).
       
    87 
       
    88     Note: ``POST`` does *not* include file-upload information. See ``FILES``.
       
    89 
       
    90 .. attribute:: HttpRequest.REQUEST
       
    91 
       
    92     For convenience, a dictionary-like object that searches ``POST`` first,
       
    93     then ``GET``. Inspired by PHP's ``$_REQUEST``.
       
    94 
       
    95     For example, if ``GET = {"name": "john"}`` and ``POST = {"age": '34'}``,
       
    96     ``REQUEST["name"]`` would be ``"john"``, and ``REQUEST["age"]`` would be
       
    97     ``"34"``.
       
    98 
       
    99     It's strongly suggested that you use ``GET`` and ``POST`` instead of
       
   100     ``REQUEST``, because the former are more explicit.
       
   101 
       
   102 .. attribute:: HttpRequest.COOKIES
       
   103 
       
   104     A standard Python dictionary containing all cookies. Keys and values are
       
   105     strings.
       
   106 
       
   107 .. attribute:: HttpRequest.FILES
       
   108 
       
   109     A dictionary-like object containing all uploaded files. Each key in
       
   110     ``FILES`` is the ``name`` from the ``<input type="file" name="" />``. Each
       
   111     value in ``FILES`` is an :class:`UploadedFile` as described below.
       
   112 
       
   113     See :doc:`/topics/files` for more information.
       
   114 
       
   115     Note that ``FILES`` will only contain data if the request method was POST
       
   116     and the ``<form>`` that posted to the request had
       
   117     ``enctype="multipart/form-data"``. Otherwise, ``FILES`` will be a blank
       
   118     dictionary-like object.
       
   119 
       
   120     .. versionchanged:: 1.0
       
   121 
       
   122     In previous versions of Django, ``request.FILES`` contained simple ``dict``
       
   123     objects representing uploaded files. This is no longer true -- files are
       
   124     represented by :class:`UploadedFile` objects.
       
   125 
       
   126     These :class:`UploadedFile` objects will emulate the old-style ``dict``
       
   127     interface, but this is deprecated and will be removed in the next release
       
   128     of Django.
       
   129 
       
   130 .. attribute:: HttpRequest.META
       
   131 
       
   132     A standard Python dictionary containing all available HTTP headers.
       
   133     Available headers depend on the client and server, but here are some
       
   134     examples:
       
   135 
       
   136         * ``CONTENT_LENGTH``
       
   137         * ``CONTENT_TYPE``
       
   138         * ``HTTP_ACCEPT_ENCODING``
       
   139         * ``HTTP_ACCEPT_LANGUAGE``
       
   140         * ``HTTP_HOST`` -- The HTTP Host header sent by the client.
       
   141         * ``HTTP_REFERER`` -- The referring page, if any.
       
   142         * ``HTTP_USER_AGENT`` -- The client's user-agent string.
       
   143         * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
       
   144         * ``REMOTE_ADDR`` -- The IP address of the client.
       
   145         * ``REMOTE_HOST`` -- The hostname of the client.
       
   146         * ``REMOTE_USER`` -- The user authenticated by the Web server, if any.
       
   147         * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
       
   148         * ``SERVER_NAME`` -- The hostname of the server.
       
   149         * ``SERVER_PORT`` -- The port of the server.
       
   150 
       
   151     With the exception of ``CONTENT_LENGTH`` and ``CONTENT_TYPE``, as given
       
   152     above, any HTTP headers in the request are converted to ``META`` keys by
       
   153     converting all characters to uppercase, replacing any hyphens with
       
   154     underscores and adding an ``HTTP_`` prefix to the name. So, for example, a
       
   155     header called ``X-Bender`` would be mapped to the ``META`` key
       
   156     ``HTTP_X_BENDER``.
       
   157 
       
   158 .. attribute:: HttpRequest.user
       
   159 
       
   160     A ``django.contrib.auth.models.User`` object representing the currently
       
   161     logged-in user. If the user isn't currently logged in, ``user`` will be set
       
   162     to an instance of ``django.contrib.auth.models.AnonymousUser``. You
       
   163     can tell them apart with ``is_authenticated()``, like so::
       
   164 
       
   165         if request.user.is_authenticated():
       
   166             # Do something for logged-in users.
       
   167         else:
       
   168             # Do something for anonymous users.
       
   169 
       
   170     ``user`` is only available if your Django installation has the
       
   171     ``AuthenticationMiddleware`` activated. For more, see
       
   172     :doc:`/topics/auth`.
       
   173 
       
   174 .. attribute:: HttpRequest.session
       
   175 
       
   176     A readable-and-writable, dictionary-like object that represents the current
       
   177     session. This is only available if your Django installation has session
       
   178     support activated. See the :doc:`session documentation
       
   179     </topics/http/sessions>` for full details.
       
   180 
       
   181 .. attribute:: HttpRequest.raw_post_data
       
   182 
       
   183     The raw HTTP POST data. This is only useful for advanced processing. Use
       
   184     ``POST`` instead.
       
   185 
       
   186 .. attribute:: HttpRequest.urlconf
       
   187 
       
   188     Not defined by Django itself, but will be read if other code (e.g., a custom
       
   189     middleware class) sets it. When present, this will be used as the root
       
   190     URLconf for the current request, overriding the :setting:`ROOT_URLCONF`
       
   191     setting. See :ref:`how-django-processes-a-request` for details.
       
   192 
       
   193 Methods
       
   194 -------
       
   195 
       
   196 .. method:: HttpRequest.get_host()
       
   197 
       
   198     Returns the originating host of the request using information from the
       
   199     ``HTTP_X_FORWARDED_HOST`` and ``HTTP_HOST`` headers (in that order). If
       
   200     they don't provide a value, the method uses a combination of
       
   201     ``SERVER_NAME`` and ``SERVER_PORT`` as detailed in `PEP 333`_.
       
   202 
       
   203     .. _PEP 333: http://www.python.org/dev/peps/pep-0333/
       
   204 
       
   205     Example: ``"127.0.0.1:8000"``
       
   206 
       
   207     .. note:: The :meth:`~HttpRequest.get_host()` method fails when the host is
       
   208         behind multiple proxies. One solution is to use middleware to rewrite
       
   209         the proxy headers, as in the following example::
       
   210 
       
   211             class MultipleProxyMiddleware(object):
       
   212                 FORWARDED_FOR_FIELDS = [
       
   213                     'HTTP_X_FORWARDED_FOR',
       
   214                     'HTTP_X_FORWARDED_HOST',
       
   215                     'HTTP_X_FORWARDED_SERVER',
       
   216                 ]
       
   217 
       
   218                 def process_request(self, request):
       
   219                     """
       
   220                     Rewrites the proxy headers so that only the most
       
   221                     recent proxy is used.
       
   222                     """
       
   223                     for field in self.FORWARDED_FOR_FIELDS:
       
   224                         if field in request.META:
       
   225                             if ',' in request.META[field]:
       
   226                                 parts = request.META[field].split(',')
       
   227                                 request.META[field] = parts[-1].strip()
       
   228 
       
   229 
       
   230 .. method:: HttpRequest.get_full_path()
       
   231 
       
   232    Returns the ``path``, plus an appended query string, if applicable.
       
   233 
       
   234    Example: ``"/music/bands/the_beatles/?print=true"``
       
   235 
       
   236 .. method:: HttpRequest.build_absolute_uri(location)
       
   237 
       
   238    Returns the absolute URI form of ``location``. If no location is provided,
       
   239    the location will be set to ``request.get_full_path()``.
       
   240 
       
   241    If the location is already an absolute URI, it will not be altered.
       
   242    Otherwise the absolute URI is built using the server variables available in
       
   243    this request.
       
   244 
       
   245    Example: ``"http://example.com/music/bands/the_beatles/?print=true"``
       
   246 
       
   247 .. method:: HttpRequest.is_secure()
       
   248 
       
   249    Returns ``True`` if the request is secure; that is, if it was made with
       
   250    HTTPS.
       
   251 
       
   252 .. method:: HttpRequest.is_ajax()
       
   253 
       
   254    Returns ``True`` if the request was made via an ``XMLHttpRequest``, by
       
   255    checking the ``HTTP_X_REQUESTED_WITH`` header for the string
       
   256    ``'XMLHttpRequest'``. Most modern JavaScript libraries send this header.
       
   257    If you write your own XMLHttpRequest call (on the browser side), you'll
       
   258    have to set this header manually if you want ``is_ajax()`` to work.
       
   259 
       
   260 
       
   261 UploadedFile objects
       
   262 ====================
       
   263 
       
   264 .. class:: UploadedFile
       
   265 
       
   266 
       
   267 Attributes
       
   268 ----------
       
   269 
       
   270 .. attribute::  UploadedFile.name
       
   271 
       
   272     The name of the uploaded file.
       
   273 
       
   274 .. attribute:: UploadedFile.size
       
   275 
       
   276     The size, in bytes, of the uploaded file.
       
   277 
       
   278 Methods
       
   279 ----------
       
   280 
       
   281 .. method:: UploadedFile.chunks(chunk_size=None)
       
   282 
       
   283     Returns a generator that yields sequential chunks of data.
       
   284 
       
   285 .. method:: UploadedFile.read(num_bytes=None)
       
   286 
       
   287     Read a number of bytes from the file.
       
   288 
       
   289 
       
   290 
       
   291 QueryDict objects
       
   292 =================
       
   293 
       
   294 .. class:: QueryDict
       
   295 
       
   296 In an :class:`HttpRequest` object, the ``GET`` and ``POST`` attributes are instances
       
   297 of ``django.http.QueryDict``. :class:`QueryDict` is a dictionary-like
       
   298 class customized to deal with multiple values for the same key. This is
       
   299 necessary because some HTML form elements, notably
       
   300 ``<select multiple="multiple">``, pass multiple values for the same key.
       
   301 
       
   302 ``QueryDict`` instances are immutable, unless you create a ``copy()`` of them.
       
   303 That means you can't change attributes of ``request.POST`` and ``request.GET``
       
   304 directly.
       
   305 
       
   306 Methods
       
   307 -------
       
   308 
       
   309 :class:`QueryDict` implements all the standard dictionary methods, because it's
       
   310 a subclass of dictionary. Exceptions are outlined here:
       
   311 
       
   312 .. method:: QueryDict.__getitem__(key)
       
   313 
       
   314     Returns the value for the given key. If the key has more than one value,
       
   315     ``__getitem__()`` returns the last value. Raises
       
   316     ``django.utils.datastructures.MultiValueDictKeyError`` if the key does not
       
   317     exist. (This is a subclass of Python's standard ``KeyError``, so you can
       
   318     stick to catching ``KeyError``.)
       
   319 
       
   320 .. method:: QueryDict.__setitem__(key, value)
       
   321 
       
   322     Sets the given key to ``[value]`` (a Python list whose single element is
       
   323     ``value``). Note that this, as other dictionary functions that have side
       
   324     effects, can only be called on a mutable ``QueryDict`` (one that was created
       
   325     via ``copy()``).
       
   326 
       
   327 .. method:: QueryDict.__contains__(key)
       
   328 
       
   329     Returns ``True`` if the given key is set. This lets you do, e.g., ``if "foo"
       
   330     in request.GET``.
       
   331 
       
   332 .. method:: QueryDict.get(key, default)
       
   333 
       
   334     Uses the same logic as ``__getitem__()`` above, with a hook for returning a
       
   335     default value if the key doesn't exist.
       
   336 
       
   337 .. method:: QueryDict.setdefault(key, default)
       
   338 
       
   339     Just like the standard dictionary ``setdefault()`` method, except it uses
       
   340     ``__setitem__()`` internally.
       
   341 
       
   342 .. method:: QueryDict.update(other_dict)
       
   343 
       
   344     Takes either a ``QueryDict`` or standard dictionary. Just like the standard
       
   345     dictionary ``update()`` method, except it *appends* to the current
       
   346     dictionary items rather than replacing them. For example::
       
   347 
       
   348           >>> q = QueryDict('a=1')
       
   349           >>> q = q.copy() # to make it mutable
       
   350           >>> q.update({'a': '2'})
       
   351           >>> q.getlist('a')
       
   352           [u'1', u'2']
       
   353           >>> q['a'] # returns the last
       
   354           [u'2']
       
   355 
       
   356 .. method:: QueryDict.items()
       
   357 
       
   358     Just like the standard dictionary ``items()`` method, except this uses the
       
   359     same last-value logic as ``__getitem__()``. For example::
       
   360 
       
   361            >>> q = QueryDict('a=1&a=2&a=3')
       
   362            >>> q.items()
       
   363            [(u'a', u'3')]
       
   364 
       
   365 .. method:: QueryDict.iteritems()
       
   366 
       
   367     Just like the standard dictionary ``iteritems()`` method. Like
       
   368     :meth:`QueryDict.items()` this uses the same last-value logic as
       
   369     :meth:`QueryDict.__getitem__()`.
       
   370 
       
   371 .. method:: QueryDict.iterlists()
       
   372 
       
   373     Like :meth:`QueryDict.iteritems()` except it includes all values, as a list,
       
   374     for each member of the dictionary.
       
   375 
       
   376 .. method:: QueryDict.values()
       
   377 
       
   378     Just like the standard dictionary ``values()`` method, except this uses the
       
   379     same last-value logic as ``__getitem__()``. For example::
       
   380 
       
   381            >>> q = QueryDict('a=1&a=2&a=3')
       
   382            >>> q.values()
       
   383            [u'3']
       
   384 
       
   385 .. method:: QueryDict.itervalues()
       
   386 
       
   387     Just like :meth:`QueryDict.values()`, except an iterator.
       
   388 
       
   389 In addition, ``QueryDict`` has the following methods:
       
   390 
       
   391 .. method:: QueryDict.copy()
       
   392 
       
   393     Returns a copy of the object, using ``copy.deepcopy()`` from the Python
       
   394     standard library. The copy will be mutable -- that is, you can change its
       
   395     values.
       
   396 
       
   397 .. method:: QueryDict.getlist(key)
       
   398 
       
   399     Returns the data with the requested key, as a Python list. Returns an
       
   400     empty list if the key doesn't exist. It's guaranteed to return a list of
       
   401     some sort.
       
   402 
       
   403 .. method:: QueryDict.setlist(key, list_)
       
   404 
       
   405     Sets the given key to ``list_`` (unlike ``__setitem__()``).
       
   406 
       
   407 .. method:: QueryDict.appendlist(key, item)
       
   408 
       
   409     Appends an item to the internal list associated with key.
       
   410 
       
   411 .. method:: QueryDict.setlistdefault(key, default_list)
       
   412 
       
   413     Just like ``setdefault``, except it takes a list of values instead of a
       
   414     single value.
       
   415 
       
   416 .. method:: QueryDict.lists()
       
   417 
       
   418     Like :meth:`items()`, except it includes all values, as a list, for each
       
   419     member of the dictionary. For example::
       
   420 
       
   421          >>> q = QueryDict('a=1&a=2&a=3')
       
   422          >>> q.lists()
       
   423          [(u'a', [u'1', u'2', u'3'])]
       
   424 
       
   425 .. method:: QueryDict.urlencode()
       
   426 
       
   427     Returns a string of the data in query-string format.
       
   428     Example: ``"a=2&b=3&b=5"``.
       
   429 
       
   430 HttpResponse objects
       
   431 ====================
       
   432 
       
   433 .. class:: HttpResponse
       
   434 
       
   435 In contrast to :class:`HttpRequest` objects, which are created automatically by
       
   436 Django, :class:`HttpResponse` objects are your responsibility. Each view you
       
   437 write is responsible for instantiating, populating and returning an
       
   438 :class:`HttpResponse`.
       
   439 
       
   440 The :class:`HttpResponse` class lives in the :mod:`django.http` module.
       
   441 
       
   442 Usage
       
   443 -----
       
   444 
       
   445 Passing strings
       
   446 ~~~~~~~~~~~~~~~
       
   447 
       
   448 Typical usage is to pass the contents of the page, as a string, to the
       
   449 :class:`HttpResponse` constructor::
       
   450 
       
   451     >>> response = HttpResponse("Here's the text of the Web page.")
       
   452     >>> response = HttpResponse("Text only, please.", mimetype="text/plain")
       
   453 
       
   454 But if you want to add content incrementally, you can use ``response`` as a
       
   455 file-like object::
       
   456 
       
   457     >>> response = HttpResponse()
       
   458     >>> response.write("<p>Here's the text of the Web page.</p>")
       
   459     >>> response.write("<p>Here's another paragraph.</p>")
       
   460 
       
   461 Passing iterators
       
   462 ~~~~~~~~~~~~~~~~~
       
   463 
       
   464 Finally, you can pass ``HttpResponse`` an iterator rather than passing it
       
   465 hard-coded strings. If you use this technique, follow these guidelines:
       
   466 
       
   467     * The iterator should return strings.
       
   468     * If an :class:`HttpResponse` has been initialized with an iterator as its
       
   469       content, you can't use the class:`HttpResponse` instance as a file-like
       
   470       object. Doing so will raise ``Exception``.
       
   471 
       
   472 Setting headers
       
   473 ~~~~~~~~~~~~~~~
       
   474 
       
   475 To set or remove a header in your response, treat it like a dictionary::
       
   476 
       
   477     >>> response = HttpResponse()
       
   478     >>> response['Cache-Control'] = 'no-cache'
       
   479     >>> del response['Cache-Control']
       
   480 
       
   481 Note that unlike a dictionary, ``del`` doesn't raise ``KeyError`` if the header
       
   482 doesn't exist.
       
   483 
       
   484 .. versionadded:: 1.1
       
   485 
       
   486 HTTP headers cannot contain newlines. An attempt to set a header containing a
       
   487 newline character (CR or LF) will raise ``BadHeaderError``
       
   488 
       
   489 Telling the browser to treat the response as a file attachment
       
   490 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   491 
       
   492 To tell the browser to treat the response as a file attachment, use the
       
   493 ``mimetype`` argument and set the ``Content-Disposition`` header. For example,
       
   494 this is how you might return a Microsoft Excel spreadsheet::
       
   495 
       
   496     >>> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel')
       
   497     >>> response['Content-Disposition'] = 'attachment; filename=foo.xls'
       
   498 
       
   499 There's nothing Django-specific about the ``Content-Disposition`` header, but
       
   500 it's easy to forget the syntax, so we've included it here.
       
   501 
       
   502 Attributes
       
   503 ----------
       
   504 
       
   505 .. attribute:: HttpResponse.content
       
   506 
       
   507     A normal Python string representing the content, encoded from a Unicode
       
   508     object if necessary.
       
   509 
       
   510 .. attribute:: HttpResponse.status_code
       
   511 
       
   512     The `HTTP Status code`_ for the response.
       
   513 
       
   514 Methods
       
   515 -------
       
   516 
       
   517 .. method:: HttpResponse.__init__(content='', mimetype=None, status=200, content_type=DEFAULT_CONTENT_TYPE)
       
   518 
       
   519     Instantiates an ``HttpResponse`` object with the given page content (a
       
   520     string) and MIME type. The :setting:`DEFAULT_CONTENT_TYPE` is
       
   521     ``'text/html'``.
       
   522 
       
   523     ``content`` can be an iterator or a string. If it's an iterator, it should
       
   524     return strings, and those strings will be joined together to form the
       
   525     content of the response.
       
   526 
       
   527     ``status`` is the `HTTP Status code`_ for the response.
       
   528 
       
   529     ``content_type`` is an alias for ``mimetype``. Historically, this parameter
       
   530     was only called ``mimetype``, but since this is actually the value included
       
   531     in the HTTP ``Content-Type`` header, it can also include the character set
       
   532     encoding, which makes it more than just a MIME type specification.
       
   533     If ``mimetype`` is specified (not ``None``), that value is used.
       
   534     Otherwise, ``content_type`` is used. If neither is given, the
       
   535     :setting:`DEFAULT_CONTENT_TYPE` setting is used.
       
   536 
       
   537 .. method:: HttpResponse.__setitem__(header, value)
       
   538 
       
   539     Sets the given header name to the given value. Both ``header`` and
       
   540     ``value`` should be strings.
       
   541 
       
   542 .. method:: HttpResponse.__delitem__(header)
       
   543 
       
   544     Deletes the header with the given name. Fails silently if the header
       
   545     doesn't exist. Case-insensitive.
       
   546 
       
   547 .. method:: HttpResponse.__getitem__(header)
       
   548 
       
   549     Returns the value for the given header name. Case-insensitive.
       
   550 
       
   551 .. method:: HttpResponse.has_header(header)
       
   552 
       
   553     Returns ``True`` or ``False`` based on a case-insensitive check for a
       
   554     header with the given name.
       
   555 
       
   556 .. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)
       
   557 
       
   558     Sets a cookie. The parameters are the same as in the `cookie Morsel`_
       
   559     object in the Python standard library.
       
   560 
       
   561         * ``max_age`` should be a number of seconds, or ``None`` (default) if
       
   562           the cookie should last only as long as the client's browser session.
       
   563         * ``expires`` should be a string in the format
       
   564           ``"Wdy, DD-Mon-YY HH:MM:SS GMT"``.
       
   565         * Use ``domain`` if you want to set a cross-domain cookie. For example,
       
   566           ``domain=".lawrence.com"`` will set a cookie that is readable by
       
   567           the domains www.lawrence.com, blogs.lawrence.com and
       
   568           calendars.lawrence.com. Otherwise, a cookie will only be readable by
       
   569           the domain that set it.
       
   570 
       
   571     .. _`cookie Morsel`: http://docs.python.org/library/cookie.html#Cookie.Morsel
       
   572 
       
   573 .. method:: HttpResponse.delete_cookie(key, path='/', domain=None)
       
   574 
       
   575     Deletes the cookie with the given key. Fails silently if the key doesn't
       
   576     exist.
       
   577 
       
   578     Due to the way cookies work, ``path`` and ``domain`` should be the same
       
   579     values you used in ``set_cookie()`` -- otherwise the cookie may not be
       
   580     deleted.
       
   581 
       
   582 .. method:: HttpResponse.write(content)
       
   583 
       
   584     This method makes an :class:`HttpResponse` instance a file-like object.
       
   585 
       
   586 .. method:: HttpResponse.flush()
       
   587 
       
   588     This method makes an :class:`HttpResponse` instance a file-like object.
       
   589 
       
   590 .. method:: HttpResponse.tell()
       
   591 
       
   592     This method makes an :class:`HttpResponse` instance a file-like object.
       
   593 
       
   594 .. _HTTP Status code: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
       
   595 
       
   596 
       
   597 .. _ref-httpresponse-subclasses:
       
   598 
       
   599 HttpResponse subclasses
       
   600 -----------------------
       
   601 
       
   602 Django includes a number of ``HttpResponse`` subclasses that handle different
       
   603 types of HTTP responses. Like ``HttpResponse``, these subclasses live in
       
   604 :mod:`django.http`.
       
   605 
       
   606 .. class:: HttpResponseRedirect
       
   607 
       
   608     The constructor takes a single argument -- the path to redirect to. This
       
   609     can be a fully qualified URL (e.g. ``'http://www.yahoo.com/search/'``) or
       
   610     an absolute path with no domain (e.g. ``'/search/'``). Note that this
       
   611     returns an HTTP status code 302.
       
   612 
       
   613 .. class:: HttpResponsePermanentRedirect
       
   614 
       
   615     Like :class:`HttpResponseRedirect`, but it returns a permanent redirect
       
   616     (HTTP status code 301) instead of a "found" redirect (status code 302).
       
   617 
       
   618 .. class:: HttpResponseNotModified
       
   619 
       
   620     The constructor doesn't take any arguments. Use this to designate that a
       
   621     page hasn't been modified since the user's last request (status code 304).
       
   622 
       
   623 .. class:: HttpResponseBadRequest
       
   624 
       
   625     Acts just like :class:`HttpResponse` but uses a 400 status code.
       
   626 
       
   627 .. class:: HttpResponseNotFound
       
   628 
       
   629     Acts just like :class:`HttpResponse` but uses a 404 status code.
       
   630 
       
   631 .. class:: HttpResponseForbidden
       
   632 
       
   633     Acts just like :class:`HttpResponse` but uses a 403 status code.
       
   634 
       
   635 .. class:: HttpResponseNotAllowed
       
   636 
       
   637     Like :class:`HttpResponse`, but uses a 405 status code. Takes a single,
       
   638     required argument: a list of permitted methods (e.g. ``['GET', 'POST']``).
       
   639 
       
   640 .. class:: HttpResponseGone
       
   641 
       
   642     Acts just like :class:`HttpResponse` but uses a 410 status code.
       
   643 
       
   644 .. class:: HttpResponseServerError
       
   645 
       
   646     Acts just like :class:`HttpResponse` but uses a 500 status code.