Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Added docs/request_response.txt

git-svn-id: http://code.djangoproject.com/svn/django/trunk@592 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit b483f66efefca1029d6ac8b9836f9db844ced05f 1 parent af8b7ff
Adrian Holovaty authored September 01, 2005

Showing 1 changed file with 312 additions and 0 deletions. Show diff stats Hide diff stats

  1. 312  docs/request_response.txt
312  docs/request_response.txt
... ...
@@ -0,0 +1,312 @@
  1
+============================
  2
+Request and response objects
  3
+============================
  4
+
  5
+Quick overview
  6
+==============
  7
+
  8
+Django uses request and response objects to pass state through the system.
  9
+
  10
+When a page is requested, Django creates an ``HttpRequest`` object that
  11
+contains metadata about the request. Then Django loads the appropriate view,
  12
+passing the ``HttpRequest`` as the first argument to the view function. Each
  13
+view is responsible for returning an ``HttpResponse`` object.
  14
+
  15
+This document explains the APIs for ``HttpRequest`` and ``HttpResponse``
  16
+objects.
  17
+
  18
+HttpRequest objects
  19
+===================
  20
+
  21
+Attributes
  22
+----------
  23
+
  24
+All attributes except ``session`` should be considered read-only.
  25
+
  26
+``path``
  27
+    A string representing the full path to the requested page, not including
  28
+    the domain.
  29
+
  30
+    Example: ``"/music/bands/the_beatles/"``
  31
+
  32
+``GET``
  33
+    A dictionary-like object containing all given HTTP GET parameters. See the
  34
+    ``MultiValueDict`` documentation below.
  35
+
  36
+``POST``
  37
+    A dictionary-like object containing all given HTTP POST parameters. See the
  38
+    ``MultiValueDict`` documentation below.
  39
+
  40
+``REQUEST``
  41
+    For convenience, a dictionary-like object that searches ``POST`` first,
  42
+    then ``GET``. Inspired by PHP's ``$_REQUEST``.
  43
+
  44
+    For example, if ``GET = {"name": "john"}`` and ``POST = {"age": '34'}``,
  45
+    ``REQUEST["name"]`` would be ``"john"``, and ``REQUEST["age"]`` would be
  46
+    ``"34"``.
  47
+
  48
+    It's strongly suggested that you use ``GET`` and ``POST`` instead of
  49
+    ``REQUEST``, because the former are more explicit.
  50
+
  51
+``COOKIES``
  52
+    A standard Python dictionary containing all cookies. Keys and values are
  53
+    strings.
  54
+
  55
+``FILES``
  56
+    A dictionary-like object containing all uploaded files. Each key in
  57
+    ``FILES`` is the ``name`` from the ``<input type="file" name="" />``. Each
  58
+    value in ``FILES`` is a standard Python dictionary with the following three
  59
+    keys:
  60
+
  61
+        * ``filename`` -- The name of the uploaded file, as a Python string.
  62
+        * ``content-type`` -- The content type of the uploaded file.
  63
+        * ``content`` -- The raw content of the uploaded file.
  64
+
  65
+    Note that ``FILES`` will only contain data if the request method was POST
  66
+    and the ``<form>`` that posted to the request had
  67
+    ``enctype="multipart/form-data"``. Otherwise, ``FILES`` will be a blank
  68
+    dictionary-like object.
  69
+
  70
+``META``
  71
+    A standard Python dictionary containing all available HTTP headers.
  72
+    Available headers depend on the client and server, but here are some
  73
+    examples:
  74
+
  75
+        * ``CONTENT_LENGTH``
  76
+        * ``CONTENT_TYPE``
  77
+        * ``HTTP_ACCEPT_ENCODING``
  78
+        * ``HTTP_ACCEPT_LANGUAGE``
  79
+        * ``HTTP_REFERER`` -- The referring page, if any.
  80
+        * ``HTTP_USER_AGENT`` -- The client's user-agent string.
  81
+        * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.
  82
+        * ``REMOTE_ADDR`` -- The IP address of the client.
  83
+        * ``REMOTE_HOST`` -- The hostname of the client.
  84
+        * ``REQUEST_METHOD`` -- A string such as ``"GET"`` or ``"POST"``.
  85
+        * ``SERVER_NAME`` -- The hostname of the server.
  86
+        * ``SERVER_PORT`` -- The port of the server.
  87
+
  88
+``user``
  89
+    A ``django.models.auth.users.User`` object representing the currently
  90
+    logged-in user. If the user isn't currently logged in, ``user`` will be set
  91
+    to an instance of ``django.parts.auth.anonymoususers.AnonymousUser``. You
  92
+    can tell them apart with ``is_anonymous()``, like so::
  93
+
  94
+        if request.user.is_anonymous():
  95
+            # Do something for anonymous users.
  96
+        else:
  97
+            # Do something for logged-in users.
  98
+
  99
+``session``
  100
+    A readable-and-writable, dictionary-like object that represents the current
  101
+    session. This is only available if your Django installation has session
  102
+    support activated. See the `session documentation`_ for full details.
  103
+
  104
+    .. _`session documentation`: http://www.djangoproject.com/documentation/sessions/
  105
+
  106
+``raw_post_data``
  107
+    The raw HTTP POST data. This is only useful for advanced processing. Use
  108
+    ``POST`` instead.
  109
+
  110
+Methods
  111
+-------
  112
+
  113
+``get_full_path()``
  114
+    Returns the ``path``, plus an appended query string, if applicable.
  115
+
  116
+    Example: ``"/music/bands/the_beatles/?print=true"``
  117
+
  118
+MultiValueDict objects
  119
+----------------------
  120
+
  121
+In an ``HttpRequest`` object, the ``GET`` and ``POST`` attributes are instances
  122
+of ``django.utils.datastructures.MultiValueDict``. ``MultiValueDict`` is a
  123
+dictionary-like class customized to deal with multiple values for the same key.
  124
+This is necessary because some HTML form elements, notably
  125
+``<select multiple>``, pass multiple values for the same key.
  126
+
  127
+``MultiValueDict`` implements the following standard dictionary methods:
  128
+
  129
+    * ``__repr__()``
  130
+
  131
+    * ``__getitem__(key)`` -- Returns the value for the given key. If the key
  132
+      has more than one value, ``__getitem__()`` returns the last value.
  133
+
  134
+    * ``__setitem__(key, value)`` -- Sets the given key to ``[value]``
  135
+      (a Python list whose single element is ``value``).
  136
+
  137
+    * ``__len__()``
  138
+
  139
+    * ``get(key, default)`` -- Uses the same logic as ``__getitem__()`` above,
  140
+      with a hook for returning a default value if the key doesn't exist.
  141
+
  142
+    * ``has_key(key)``
  143
+
  144
+    * ``items()``
  145
+
  146
+    * ``keys()``
  147
+
  148
+    * ``update(other_dict)``
  149
+
  150
+In addition, it has the following methods:
  151
+
  152
+    * ``copy()`` -- Returns a copy of the object, using ``copy.deepcopy()``
  153
+      from the Python standard library.
  154
+
  155
+    * ``getlist(key)`` -- Returns the data with the requested key, as a Python
  156
+      list. Returns an empty list if the key doesn't exist.
  157
+
  158
+    * ``setlist(key, list_)`` -- Sets the given key to ``list_`` (unlike
  159
+      ``__setitem__()``).
  160
+
  161
+    * ``appendlist(key, item)`` -- Appends an item to the internal list
  162
+      associated with key.
  163
+
  164
+Examples
  165
+--------
  166
+
  167
+Here's an example HTML form and how Django would treat the input::
  168
+
  169
+    <form action="/foo/bar/" method="post">
  170
+    <input type="text" name="your_name" />
  171
+    <select multiple="multiple" name="bands">
  172
+        <option value="beatles">The Beatles</option>
  173
+        <option value="who">The Who</option>
  174
+        <option value="zombies">The Zombies</option>
  175
+    </select>
  176
+    <input type="submit" />
  177
+    </form>
  178
+
  179
+If the user enters ``"John Smith"`` in the ``your_name`` field and selects both
  180
+"The Beatles" and "The Zombies" in the multiple select box, here's what
  181
+Django's request object would have::
  182
+
  183
+    >>> request.GET
  184
+    {}
  185
+    >>> request.POST
  186
+    {'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']}
  187
+    >>> request.POST['your_name']
  188
+    'John Smith'
  189
+    >>> request.POST['bands']
  190
+    'zombies'
  191
+    >>> request.POST.getlist('bands')
  192
+    ['beatles', 'zombies']
  193
+    >>> request.POST.get('your_name', 'Adrian')
  194
+    'John Smith'
  195
+    >>> request.POST.get('nonexistent_field', 'Nowhere Man')
  196
+    'Nowhere Man'
  197
+
  198
+Implementation notes
  199
+--------------------
  200
+
  201
+The ``GET``, ``POST``, ``COOKIES``, ``FILES``, ``META``, ``REQUEST``,
  202
+``raw_post_data`` and ``user`` attributes are all lazily loaded. That means
  203
+Django doesn't spend resources calculating the values of those attributes until
  204
+your code requests them.
  205
+
  206
+HttpResponse objects
  207
+====================
  208
+
  209
+In contrast to ``HttpRequest`` objects, which are created automatically by
  210
+Django, ``HttpResponse`` objects are your responsibility. Each view you write
  211
+is responsible for instantiating, populating and returning an ``HttpResponse``.
  212
+
  213
+The ``HttpResponse`` class lives at ``django.utils.httpwrappers.HttpResponse``.
  214
+
  215
+Usage
  216
+-----
  217
+
  218
+Typical usage is to pass the contents of the page, as a string, to the
  219
+``HttpResponse`` constructor::
  220
+
  221
+    >>> response = HttpResponse("Here's the text of the Web page.")
  222
+    >>> response = HttpResponse("Text only, please.", mimetype="text/plain")
  223
+
  224
+But if you want to add content incrementally, you can use ``response`` as a
  225
+file-like object::
  226
+
  227
+    >>> response = HttpResponse()
  228
+    >>> response.write("<p>Here's the text of the Web page.</p>")
  229
+    >>> response.write("<p>Here's another paragraph.</p>")
  230
+
  231
+You can add and delete headers using dictionary syntax::
  232
+
  233
+    >>> response = HttpResponse()
  234
+    >>> response['X-DJANGO'] = "It's the best."
  235
+    >>> del response['X-PHP']
  236
+    >>> response['X-DJANGO']
  237
+    "It's the best."
  238
+
  239
+Note that ``del`` doesn't raise ``KeyError`` if the header doesn't exist.
  240
+
  241
+Methods
  242
+-------
  243
+
  244
+``__init__(content='', mimetype=DEFAULT_MIME_TYPE)``
  245
+    Instantiates an ``HttpResponse`` object with the given page content (a
  246
+    string) and MIME type. The ``DEFAULT_MIME_TYPE`` is ``"text/html"``.
  247
+
  248
+``__setitem__(header, value)``
  249
+    Sets the given header name to the given value. Both ``header`` and
  250
+    ``value`` should be strings.
  251
+
  252
+``__delitem__(header)``
  253
+    Deletes the header with the given name. Fails silently if the header
  254
+    doesn't exist. Case-sensitive.
  255
+
  256
+``__getitem__(header)``
  257
+    Returns the value for the given header name. Case-sensitive.
  258
+
  259
+``has_header(header)``
  260
+    Returns ``True`` or ``False`` based on a case-insensitive check for a
  261
+    header with the given name.
  262
+
  263
+``set_cookie(key, value='', max_age=None, path='/', domain=None, secure=None)``
  264
+    Sets a cookie. The parameters are the same as in the `Cookie.Morsel`_
  265
+    object in the Python standard library.
  266
+
  267
+        * ``max_age`` should be a number of seconds, or ``None`` (default) if
  268
+          the cookie should last only as long as the client's browser session.
  269
+        * Use ``domain`` if you want to set a cross-domain cookie. For example,
  270
+          ``domain=".lawrence.com"`` will set a cookie that is readable by
  271
+          the domains www.lawrence.com, blogs.lawrence.com and
  272
+          calendars.lawrence.com. Otherwise, a cookie will only be readable by
  273
+          the domain that set it.
  274
+
  275
+    .. _`Cookie.Morsel object`: http://www.python.org/doc/current/lib/morsel-objects.html
  276
+
  277
+``get_content_as_string(encoding)``
  278
+    Returns the content as a Python string, encoding it from a Unicode object
  279
+    if necessary.
  280
+
  281
+``write(content)``
  282
+``flush()``
  283
+``tell()``
  284
+    These methods make an ``HttpResponse`` instance a file-like object.
  285
+
  286
+HttpResponse subclasses
  287
+-----------------------
  288
+
  289
+Django includes a number of ``HttpResponse`` subclasses that handle different
  290
+types of HTTP responses. Like ``HttpResponse``, these subclasses live in
  291
+``django.utils.httpwrappers``.
  292
+
  293
+``HttpResponseRedirect``
  294
+    The constructor takes a single argument -- the path to redirect to. This
  295
+    can be a fully qualified URL (e.g. ``"http://www.yahoo.com/search/"``) or an
  296
+    absolute URL with no domain (e.g. ``"/search/"``).
  297
+
  298
+``HttpResponseNotModified``
  299
+    The constructor doesn't take any arguments. Use this to designate that a
  300
+    page hasn't been modified since the user's last request.
  301
+
  302
+``HttpResponseNotFound``
  303
+    Acts just like ``HttpResponse`` but uses a 404 status code.
  304
+
  305
+``HttpResponseForbidden``
  306
+    Acts just like ``HttpResponse`` but uses a 403 status code.
  307
+
  308
+``HttpResponseGone``
  309
+    Acts just like ``HttpResponse`` but uses a 410 status code.
  310
+
  311
+``HttpResponseServerError``
  312
+    Acts just like ``HttpResponse`` but uses a 500 status code.

0 notes on commit b483f66

Please sign in to comment.
Something went wrong with that request. Please try again.