| 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 |
``__getitem__(key)`` |
|---|
| 114 |
Returns the GET/POST value for the given key, checking POST first, then |
|---|
| 115 |
GET. Raises ``KeyError`` if the key doesn't exist. |
|---|
| 116 |
|
|---|
| 117 |
This lets you use dictionary-accessing syntax on an ``HttpRequest`` |
|---|
| 118 |
instance. Example: ``request["foo"]`` would return ``True`` if either |
|---|
| 119 |
``request.POST`` or ``request.GET`` had a ``"foo"`` key. |
|---|
| 120 |
|
|---|
| 121 |
``has_key()`` |
|---|
| 122 |
Returns ``True`` or ``False``, designating whether ``request.GET`` or |
|---|
| 123 |
``request.POST`` has the given key. |
|---|
| 124 |
|
|---|
| 125 |
``get_full_path()`` |
|---|
| 126 |
Returns the ``path``, plus an appended query string, if applicable. |
|---|
| 127 |
|
|---|
| 128 |
Example: ``"/music/bands/the_beatles/?print=true"`` |
|---|
| 129 |
|
|---|
| 130 |
QueryDict objects |
|---|
| 131 |
----------------- |
|---|
| 132 |
|
|---|
| 133 |
In an ``HttpRequest`` object, the ``GET`` and ``POST`` attributes are instances |
|---|
| 134 |
of ``django.utils.httpwrappers.QueryDict``. ``QueryDict`` is a dictionary-like |
|---|
| 135 |
class customized to deal with multiple values for the same key. This is |
|---|
| 136 |
necessary because some HTML form elements, notably ``<select multiple>``, pass |
|---|
| 137 |
multiple values for the same key. |
|---|
| 138 |
|
|---|
| 139 |
``QueryDict`` instances are immutable, unless you create a ``copy()`` of them. |
|---|
| 140 |
That means you can't change attributes of ``request.POST`` and ``request.GET`` |
|---|
| 141 |
directly. |
|---|
| 142 |
|
|---|
| 143 |
``QueryDict`` implements the following standard dictionary methods: |
|---|
| 144 |
|
|---|
| 145 |
* ``__repr__()`` |
|---|
| 146 |
|
|---|
| 147 |
* ``__getitem__(key)`` -- Returns the value for the given key. If the key |
|---|
| 148 |
has more than one value, ``__getitem__()`` returns the last value. |
|---|
| 149 |
|
|---|
| 150 |
* ``__setitem__(key, value)`` -- Sets the given key to ``[value]`` |
|---|
| 151 |
(a Python list whose single element is ``value``). |
|---|
| 152 |
|
|---|
| 153 |
* ``__len__()`` |
|---|
| 154 |
|
|---|
| 155 |
* ``get(key, default)`` -- Uses the same logic as ``__getitem__()`` above, |
|---|
| 156 |
with a hook for returning a default value if the key doesn't exist. |
|---|
| 157 |
|
|---|
| 158 |
* ``has_key(key)`` |
|---|
| 159 |
|
|---|
| 160 |
* ``items()`` -- Just like the standard dictionary ``items()`` method, |
|---|
| 161 |
except this retains the order for values of duplicate keys, if any. For |
|---|
| 162 |
example, if the original query string was ``"a=1&b=2&b=3"``, ``items()`` |
|---|
| 163 |
will return ``[("a", ["1"]), ("b", ["2", "3"])]``, where the order of |
|---|
| 164 |
``["2", "3"]`` is guaranteed, but the order of ``a`` vs. ``b`` isn't. |
|---|
| 165 |
|
|---|
| 166 |
* ``keys()`` |
|---|
| 167 |
|
|---|
| 168 |
* ``update(other_dict)`` |
|---|
| 169 |
|
|---|
| 170 |
In addition, it has the following methods: |
|---|
| 171 |
|
|---|
| 172 |
* ``copy()`` -- Returns a copy of the object, using ``copy.deepcopy()`` |
|---|
| 173 |
from the Python standard library. The copy will be mutable -- that is, |
|---|
| 174 |
you can change its values. |
|---|
| 175 |
|
|---|
| 176 |
* ``getlist(key)`` -- Returns the data with the requested key, as a Python |
|---|
| 177 |
list. Returns an empty list if the key doesn't exist. |
|---|
| 178 |
|
|---|
| 179 |
* ``setlist(key, list_)`` -- Sets the given key to ``list_`` (unlike |
|---|
| 180 |
``__setitem__()``). |
|---|
| 181 |
|
|---|
| 182 |
* ``appendlist(key, item)`` -- Appends an item to the internal list |
|---|
| 183 |
associated with key. |
|---|
| 184 |
|
|---|
| 185 |
* ``urlencode()`` -- Returns a string of the data in query-string format. |
|---|
| 186 |
Example: ``"a=2&b=3&b=5"``. |
|---|
| 187 |
|
|---|
| 188 |
Examples |
|---|
| 189 |
-------- |
|---|
| 190 |
|
|---|
| 191 |
Here's an example HTML form and how Django would treat the input:: |
|---|
| 192 |
|
|---|
| 193 |
<form action="/foo/bar/" method="post"> |
|---|
| 194 |
<input type="text" name="your_name" /> |
|---|
| 195 |
<select multiple="multiple" name="bands"> |
|---|
| 196 |
<option value="beatles">The Beatles</option> |
|---|
| 197 |
<option value="who">The Who</option> |
|---|
| 198 |
<option value="zombies">The Zombies</option> |
|---|
| 199 |
</select> |
|---|
| 200 |
<input type="submit" /> |
|---|
| 201 |
</form> |
|---|
| 202 |
|
|---|
| 203 |
If the user enters ``"John Smith"`` in the ``your_name`` field and selects both |
|---|
| 204 |
"The Beatles" and "The Zombies" in the multiple select box, here's what |
|---|
| 205 |
Django's request object would have:: |
|---|
| 206 |
|
|---|
| 207 |
>>> request.GET |
|---|
| 208 |
{} |
|---|
| 209 |
>>> request.POST |
|---|
| 210 |
{'your_name': ['John Smith'], 'bands': ['beatles', 'zombies']} |
|---|
| 211 |
>>> request.POST['your_name'] |
|---|
| 212 |
'John Smith' |
|---|
| 213 |
>>> request.POST['bands'] |
|---|
| 214 |
'zombies' |
|---|
| 215 |
>>> request.POST.getlist('bands') |
|---|
| 216 |
['beatles', 'zombies'] |
|---|
| 217 |
>>> request.POST.get('your_name', 'Adrian') |
|---|
| 218 |
'John Smith' |
|---|
| 219 |
>>> request.POST.get('nonexistent_field', 'Nowhere Man') |
|---|
| 220 |
'Nowhere Man' |
|---|
| 221 |
|
|---|
| 222 |
Implementation notes |
|---|
| 223 |
-------------------- |
|---|
| 224 |
|
|---|
| 225 |
The ``GET``, ``POST``, ``COOKIES``, ``FILES``, ``META``, ``REQUEST``, |
|---|
| 226 |
``raw_post_data`` and ``user`` attributes are all lazily loaded. That means |
|---|
| 227 |
Django doesn't spend resources calculating the values of those attributes until |
|---|
| 228 |
your code requests them. |
|---|
| 229 |
|
|---|
| 230 |
HttpResponse objects |
|---|
| 231 |
==================== |
|---|
| 232 |
|
|---|
| 233 |
In contrast to ``HttpRequest`` objects, which are created automatically by |
|---|
| 234 |
Django, ``HttpResponse`` objects are your responsibility. Each view you write |
|---|
| 235 |
is responsible for instantiating, populating and returning an ``HttpResponse``. |
|---|
| 236 |
|
|---|
| 237 |
The ``HttpResponse`` class lives at ``django.utils.httpwrappers.HttpResponse``. |
|---|
| 238 |
|
|---|
| 239 |
Usage |
|---|
| 240 |
----- |
|---|
| 241 |
|
|---|
| 242 |
Typical usage is to pass the contents of the page, as a string, to the |
|---|
| 243 |
``HttpResponse`` constructor:: |
|---|
| 244 |
|
|---|
| 245 |
>>> response = HttpResponse("Here's the text of the Web page.") |
|---|
| 246 |
>>> response = HttpResponse("Text only, please.", mimetype="text/plain") |
|---|
| 247 |
|
|---|
| 248 |
But if you want to add content incrementally, you can use ``response`` as a |
|---|
| 249 |
file-like object:: |
|---|
| 250 |
|
|---|
| 251 |
>>> response = HttpResponse() |
|---|
| 252 |
>>> response.write("<p>Here's the text of the Web page.</p>") |
|---|
| 253 |
>>> response.write("<p>Here's another paragraph.</p>") |
|---|
| 254 |
|
|---|
| 255 |
You can add and delete headers using dictionary syntax:: |
|---|
| 256 |
|
|---|
| 257 |
>>> response = HttpResponse() |
|---|
| 258 |
>>> response['X-DJANGO'] = "It's the best." |
|---|
| 259 |
>>> del response['X-PHP'] |
|---|
| 260 |
>>> response['X-DJANGO'] |
|---|
| 261 |
"It's the best." |
|---|
| 262 |
|
|---|
| 263 |
Note that ``del`` doesn't raise ``KeyError`` if the header doesn't exist. |
|---|
| 264 |
|
|---|
| 265 |
Methods |
|---|
| 266 |
------- |
|---|
| 267 |
|
|---|
| 268 |
``__init__(content='', mimetype=DEFAULT_MIME_TYPE)`` |
|---|
| 269 |
Instantiates an ``HttpResponse`` object with the given page content (a |
|---|
| 270 |
string) and MIME type. The ``DEFAULT_MIME_TYPE`` is ``"text/html"``. |
|---|
| 271 |
|
|---|
| 272 |
``__setitem__(header, value)`` |
|---|
| 273 |
Sets the given header name to the given value. Both ``header`` and |
|---|
| 274 |
``value`` should be strings. |
|---|
| 275 |
|
|---|
| 276 |
``__delitem__(header)`` |
|---|
| 277 |
Deletes the header with the given name. Fails silently if the header |
|---|
| 278 |
doesn't exist. Case-sensitive. |
|---|
| 279 |
|
|---|
| 280 |
``__getitem__(header)`` |
|---|
| 281 |
Returns the value for the given header name. Case-sensitive. |
|---|
| 282 |
|
|---|
| 283 |
``has_header(header)`` |
|---|
| 284 |
Returns ``True`` or ``False`` based on a case-insensitive check for a |
|---|
| 285 |
header with the given name. |
|---|
| 286 |
|
|---|
| 287 |
``set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None)`` |
|---|
| 288 |
Sets a cookie. The parameters are the same as in the `cookie Morsel`_ |
|---|
| 289 |
object in the Python standard library. |
|---|
| 290 |
|
|---|
| 291 |
* ``max_age`` should be a number of seconds, or ``None`` (default) if |
|---|
| 292 |
the cookie should last only as long as the client's browser session. |
|---|
| 293 |
* ``expires`` should be a string in the format |
|---|
| 294 |
``"Wdy, DD-Mon-YY HH:MM:SS GMT"``. |
|---|
| 295 |
* Use ``domain`` if you want to set a cross-domain cookie. For example, |
|---|
| 296 |
``domain=".lawrence.com"`` will set a cookie that is readable by |
|---|
| 297 |
the domains www.lawrence.com, blogs.lawrence.com and |
|---|
| 298 |
calendars.lawrence.com. Otherwise, a cookie will only be readable by |
|---|
| 299 |
the domain that set it. |
|---|
| 300 |
|
|---|
| 301 |
.. _`cookie Morsel`: http://www.python.org/doc/current/lib/morsel-objects.html |
|---|
| 302 |
|
|---|
| 303 |
``delete_cookie(key)`` |
|---|
| 304 |
Deletes the cookie with the given key. Fails silently if the key doesn't |
|---|
| 305 |
exist. |
|---|
| 306 |
|
|---|
| 307 |
``get_content_as_string(encoding)`` |
|---|
| 308 |
Returns the content as a Python string, encoding it from a Unicode object |
|---|
| 309 |
if necessary. |
|---|
| 310 |
|
|---|
| 311 |
``write(content)``, ``flush()`` and ``tell()`` |
|---|
| 312 |
These methods make an ``HttpResponse`` instance a file-like object. |
|---|
| 313 |
|
|---|
| 314 |
HttpResponse subclasses |
|---|
| 315 |
----------------------- |
|---|
| 316 |
|
|---|
| 317 |
Django includes a number of ``HttpResponse`` subclasses that handle different |
|---|
| 318 |
types of HTTP responses. Like ``HttpResponse``, these subclasses live in |
|---|
| 319 |
``django.utils.httpwrappers``. |
|---|
| 320 |
|
|---|
| 321 |
``HttpResponseRedirect`` |
|---|
| 322 |
The constructor takes a single argument -- the path to redirect to. This |
|---|
| 323 |
can be a fully qualified URL (e.g. ``"http://www.yahoo.com/search/"``) or an |
|---|
| 324 |
absolute URL with no domain (e.g. ``"/search/"``). |
|---|
| 325 |
|
|---|
| 326 |
``HttpResponseNotModified`` |
|---|
| 327 |
The constructor doesn't take any arguments. Use this to designate that a |
|---|
| 328 |
page hasn't been modified since the user's last request. |
|---|
| 329 |
|
|---|
| 330 |
``HttpResponseNotFound`` |
|---|
| 331 |
Acts just like ``HttpResponse`` but uses a 404 status code. |
|---|
| 332 |
|
|---|
| 333 |
``HttpResponseForbidden`` |
|---|
| 334 |
Acts just like ``HttpResponse`` but uses a 403 status code. |
|---|
| 335 |
|
|---|
| 336 |
``HttpResponseGone`` |
|---|
| 337 |
Acts just like ``HttpResponse`` but uses a 410 status code. |
|---|
| 338 |
|
|---|
| 339 |
``HttpResponseServerError`` |
|---|
| 340 |
Acts just like ``HttpResponse`` but uses a 500 status code. |
|---|