| 1 |
=================== |
|---|
| 2 |
How to use sessions |
|---|
| 3 |
=================== |
|---|
| 4 |
|
|---|
| 5 |
Django provides full support for anonymous sessions. The session framework lets |
|---|
| 6 |
you store and retrieve arbitrary data on a per-site-visitor basis. It stores |
|---|
| 7 |
data on the server side and abstracts the sending and receiving of cookies. |
|---|
| 8 |
Cookies contain a session ID -- not the data itself. |
|---|
| 9 |
|
|---|
| 10 |
Enabling sessions |
|---|
| 11 |
================= |
|---|
| 12 |
|
|---|
| 13 |
Sessions are implemented via a piece of middleware_. |
|---|
| 14 |
|
|---|
| 15 |
To enable session functionality, do the following: |
|---|
| 16 |
|
|---|
| 17 |
* Edit the ``MIDDLEWARE_CLASSES`` setting and make sure |
|---|
| 18 |
``MIDDLEWARE_CLASSES`` contains ``'django.contrib.sessions.middleware.SessionMiddleware'``. |
|---|
| 19 |
The default ``settings.py`` created by ``django-admin.py startproject`` has |
|---|
| 20 |
``SessionMiddleware`` activated. |
|---|
| 21 |
|
|---|
| 22 |
* Add ``'django.contrib.sessions'`` to your ``INSTALLED_APPS`` setting, |
|---|
| 23 |
and run ``manage.py syncdb`` to install the single database table |
|---|
| 24 |
that stores session data. |
|---|
| 25 |
|
|---|
| 26 |
**New in development version**: this step is optional if you're not using |
|---|
| 27 |
the database session backend; see `configuring the session engine`_. |
|---|
| 28 |
|
|---|
| 29 |
If you don't want to use sessions, you might as well remove the |
|---|
| 30 |
``SessionMiddleware`` line from ``MIDDLEWARE_CLASSES`` and ``'django.contrib.sessions'`` |
|---|
| 31 |
from your ``INSTALLED_APPS``. It'll save you a small bit of overhead. |
|---|
| 32 |
|
|---|
| 33 |
.. _middleware: ../middleware/ |
|---|
| 34 |
|
|---|
| 35 |
Configuring the session engine |
|---|
| 36 |
============================== |
|---|
| 37 |
|
|---|
| 38 |
**New in development version**. |
|---|
| 39 |
|
|---|
| 40 |
By default, Django stores sessions in your database (using the model |
|---|
| 41 |
``django.contrib.sessions.models.Session``). Though this is convenient, in |
|---|
| 42 |
some setups it's faster to store session data elsewhere, so Django can be |
|---|
| 43 |
configured to store session data on your filesystem or in your cache. |
|---|
| 44 |
|
|---|
| 45 |
Using file-based sessions |
|---|
| 46 |
------------------------- |
|---|
| 47 |
|
|---|
| 48 |
To use file-based sessions, set the ``SESSION_ENGINE`` setting to |
|---|
| 49 |
``"django.contrib.sessions.backends.file"``. |
|---|
| 50 |
|
|---|
| 51 |
You might also want to set the ``SESSION_FILE_PATH`` setting (which defaults |
|---|
| 52 |
to output from ``tempfile.gettempdir()``, most likely ``/tmp``) to control |
|---|
| 53 |
where Django stores session files. Be sure to check that your Web server has |
|---|
| 54 |
permissions to read and write to this location. |
|---|
| 55 |
|
|---|
| 56 |
Using cache-based sessions |
|---|
| 57 |
-------------------------- |
|---|
| 58 |
|
|---|
| 59 |
To store session data using Django's cache system, set ``SESSION_ENGINE`` |
|---|
| 60 |
to ``"django.contrib.sessions.backends.cache"``. You'll want to make sure |
|---|
| 61 |
you've configured your cache; see the `cache documentation`_ for details. |
|---|
| 62 |
|
|---|
| 63 |
.. _cache documentation: ../cache/ |
|---|
| 64 |
|
|---|
| 65 |
.. note:: |
|---|
| 66 |
|
|---|
| 67 |
You should probably only use cache-based sessions if you're using the |
|---|
| 68 |
memcached cache backend. The local memory and simple cache backends |
|---|
| 69 |
don't retain data long enough to be good choices, and it'll be faster |
|---|
| 70 |
to use file or database sessions directly instead of sending everything |
|---|
| 71 |
through the file or database cache backends. |
|---|
| 72 |
|
|---|
| 73 |
Using sessions in views |
|---|
| 74 |
======================= |
|---|
| 75 |
|
|---|
| 76 |
When ``SessionMiddleware`` is activated, each ``HttpRequest`` object -- the |
|---|
| 77 |
first argument to any Django view function -- will have a ``session`` |
|---|
| 78 |
attribute, which is a dictionary-like object. You can read it and write to it. |
|---|
| 79 |
|
|---|
| 80 |
It implements the following standard dictionary methods: |
|---|
| 81 |
|
|---|
| 82 |
* ``__getitem__(key)`` |
|---|
| 83 |
Example: ``fav_color = request.session['fav_color']`` |
|---|
| 84 |
|
|---|
| 85 |
* ``__setitem__(key, value)`` |
|---|
| 86 |
Example: ``request.session['fav_color'] = 'blue'`` |
|---|
| 87 |
|
|---|
| 88 |
* ``__delitem__(key)`` |
|---|
| 89 |
Example: ``del request.session['fav_color']``. This raises ``KeyError`` |
|---|
| 90 |
if the given ``key`` isn't already in the session. |
|---|
| 91 |
|
|---|
| 92 |
* ``__contains__(key)`` |
|---|
| 93 |
Example: ``'fav_color' in request.session`` |
|---|
| 94 |
|
|---|
| 95 |
* ``get(key, default=None)`` |
|---|
| 96 |
Example: ``fav_color = request.session.get('fav_color', 'red')`` |
|---|
| 97 |
|
|---|
| 98 |
* ``keys()`` |
|---|
| 99 |
|
|---|
| 100 |
* ``items()`` |
|---|
| 101 |
|
|---|
| 102 |
* ``setdefault()`` (**New in Django development version**) |
|---|
| 103 |
|
|---|
| 104 |
It also has these three methods: |
|---|
| 105 |
|
|---|
| 106 |
* ``set_test_cookie()`` |
|---|
| 107 |
Sets a test cookie to determine whether the user's browser supports |
|---|
| 108 |
cookies. Due to the way cookies work, you won't be able to test this |
|---|
| 109 |
until the user's next page request. See "Setting test cookies" below for |
|---|
| 110 |
more information. |
|---|
| 111 |
|
|---|
| 112 |
* ``test_cookie_worked()`` |
|---|
| 113 |
Returns either ``True`` or ``False``, depending on whether the user's |
|---|
| 114 |
browser accepted the test cookie. Due to the way cookies work, you'll |
|---|
| 115 |
have to call ``set_test_cookie()`` on a previous, separate page request. |
|---|
| 116 |
See "Setting test cookies" below for more information. |
|---|
| 117 |
|
|---|
| 118 |
* ``delete_test_cookie()`` |
|---|
| 119 |
Deletes the test cookie. Use this to clean up after yourself. |
|---|
| 120 |
|
|---|
| 121 |
You can edit ``request.session`` at any point in your view. You can edit it |
|---|
| 122 |
multiple times. |
|---|
| 123 |
|
|---|
| 124 |
Session object guidelines |
|---|
| 125 |
------------------------- |
|---|
| 126 |
|
|---|
| 127 |
* Use normal Python strings as dictionary keys on ``request.session``. This |
|---|
| 128 |
is more of a convention than a hard-and-fast rule. |
|---|
| 129 |
|
|---|
| 130 |
* Session dictionary keys that begin with an underscore are reserved for |
|---|
| 131 |
internal use by Django. |
|---|
| 132 |
|
|---|
| 133 |
* Don't override ``request.session`` with a new object, and don't access or |
|---|
| 134 |
set its attributes. Use it like a Python dictionary. |
|---|
| 135 |
|
|---|
| 136 |
Examples |
|---|
| 137 |
-------- |
|---|
| 138 |
|
|---|
| 139 |
This simplistic view sets a ``has_commented`` variable to ``True`` after a user |
|---|
| 140 |
posts a comment. It doesn't let a user post a comment more than once:: |
|---|
| 141 |
|
|---|
| 142 |
def post_comment(request, new_comment): |
|---|
| 143 |
if request.session.get('has_commented', False): |
|---|
| 144 |
return HttpResponse("You've already commented.") |
|---|
| 145 |
c = comments.Comment(comment=new_comment) |
|---|
| 146 |
c.save() |
|---|
| 147 |
request.session['has_commented'] = True |
|---|
| 148 |
return HttpResponse('Thanks for your comment!') |
|---|
| 149 |
|
|---|
| 150 |
This simplistic view logs in a "member" of the site:: |
|---|
| 151 |
|
|---|
| 152 |
def login(request): |
|---|
| 153 |
m = Member.objects.get(username=request.POST['username']) |
|---|
| 154 |
if m.password == request.POST['password']: |
|---|
| 155 |
request.session['member_id'] = m.id |
|---|
| 156 |
return HttpResponse("You're logged in.") |
|---|
| 157 |
else: |
|---|
| 158 |
return HttpResponse("Your username and password didn't match.") |
|---|
| 159 |
|
|---|
| 160 |
...And this one logs a member out, according to ``login()`` above:: |
|---|
| 161 |
|
|---|
| 162 |
def logout(request): |
|---|
| 163 |
try: |
|---|
| 164 |
del request.session['member_id'] |
|---|
| 165 |
except KeyError: |
|---|
| 166 |
pass |
|---|
| 167 |
return HttpResponse("You're logged out.") |
|---|
| 168 |
|
|---|
| 169 |
Setting test cookies |
|---|
| 170 |
==================== |
|---|
| 171 |
|
|---|
| 172 |
As a convenience, Django provides an easy way to test whether the user's |
|---|
| 173 |
browser accepts cookies. Just call ``request.session.set_test_cookie()`` in a |
|---|
| 174 |
view, and call ``request.session.test_cookie_worked()`` in a subsequent view -- |
|---|
| 175 |
not in the same view call. |
|---|
| 176 |
|
|---|
| 177 |
This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()`` |
|---|
| 178 |
is necessary due to the way cookies work. When you set a cookie, you can't |
|---|
| 179 |
actually tell whether a browser accepted it until the browser's next request. |
|---|
| 180 |
|
|---|
| 181 |
It's good practice to use ``delete_test_cookie()`` to clean up after yourself. |
|---|
| 182 |
Do this after you've verified that the test cookie worked. |
|---|
| 183 |
|
|---|
| 184 |
Here's a typical usage example:: |
|---|
| 185 |
|
|---|
| 186 |
def login(request): |
|---|
| 187 |
if request.method == 'POST': |
|---|
| 188 |
if request.session.test_cookie_worked(): |
|---|
| 189 |
request.session.delete_test_cookie() |
|---|
| 190 |
return HttpResponse("You're logged in.") |
|---|
| 191 |
else: |
|---|
| 192 |
return HttpResponse("Please enable cookies and try again.") |
|---|
| 193 |
request.session.set_test_cookie() |
|---|
| 194 |
return render_to_response('foo/login_form.html') |
|---|
| 195 |
|
|---|
| 196 |
Using sessions out of views |
|---|
| 197 |
=========================== |
|---|
| 198 |
|
|---|
| 199 |
**New in Django development version** |
|---|
| 200 |
|
|---|
| 201 |
An API is available to manipulate session data outside of a view:: |
|---|
| 202 |
|
|---|
| 203 |
>>> from django.contrib.sessions.backends.db import SessionStore |
|---|
| 204 |
>>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead') |
|---|
| 205 |
>>> s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10) |
|---|
| 206 |
>>> s['last_login'] |
|---|
| 207 |
datetime.datetime(2005, 8, 20, 13, 35, 0) |
|---|
| 208 |
>>> s.save() |
|---|
| 209 |
|
|---|
| 210 |
If you're using the ``django.contrib.sessions.backends.db`` backend, each |
|---|
| 211 |
session is just a normal Django model. The ``Session`` model is defined in |
|---|
| 212 |
``django/contrib/sessions/models.py``. Because it's a normal model, you can |
|---|
| 213 |
access sessions using the normal Django database API:: |
|---|
| 214 |
|
|---|
| 215 |
>>> from django.contrib.sessions.models import Session |
|---|
| 216 |
>>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead') |
|---|
| 217 |
>>> s.expire_date |
|---|
| 218 |
datetime.datetime(2005, 8, 20, 13, 35, 12) |
|---|
| 219 |
|
|---|
| 220 |
Note that you'll need to call ``get_decoded()`` to get the session dictionary. |
|---|
| 221 |
This is necessary because the dictionary is stored in an encoded format:: |
|---|
| 222 |
|
|---|
| 223 |
>>> s.session_data |
|---|
| 224 |
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...' |
|---|
| 225 |
>>> s.get_decoded() |
|---|
| 226 |
{'user_id': 42} |
|---|
| 227 |
|
|---|
| 228 |
When sessions are saved |
|---|
| 229 |
======================= |
|---|
| 230 |
|
|---|
| 231 |
By default, Django only saves to the session database when the session has been |
|---|
| 232 |
modified -- that is if any of its dictionary values have been assigned or |
|---|
| 233 |
deleted:: |
|---|
| 234 |
|
|---|
| 235 |
# Session is modified. |
|---|
| 236 |
request.session['foo'] = 'bar' |
|---|
| 237 |
|
|---|
| 238 |
# Session is modified. |
|---|
| 239 |
del request.session['foo'] |
|---|
| 240 |
|
|---|
| 241 |
# Session is modified. |
|---|
| 242 |
request.session['foo'] = {} |
|---|
| 243 |
|
|---|
| 244 |
# Gotcha: Session is NOT modified, because this alters |
|---|
| 245 |
# request.session['foo'] instead of request.session. |
|---|
| 246 |
request.session['foo']['bar'] = 'baz' |
|---|
| 247 |
|
|---|
| 248 |
In the last case of the above example, we can tell the session object |
|---|
| 249 |
explicitly that it has been modified by setting the ``modified`` attribute on |
|---|
| 250 |
the session object:: |
|---|
| 251 |
|
|---|
| 252 |
request.session.modified = True |
|---|
| 253 |
|
|---|
| 254 |
To change this default behavior, set the ``SESSION_SAVE_EVERY_REQUEST`` setting |
|---|
| 255 |
to ``True``. If ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, Django will save |
|---|
| 256 |
the session to the database on every single request. |
|---|
| 257 |
|
|---|
| 258 |
Note that the session cookie is only sent when a session has been created or |
|---|
| 259 |
modified. If ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, the session cookie |
|---|
| 260 |
will be sent on every request. |
|---|
| 261 |
|
|---|
| 262 |
Similarly, the ``expires`` part of a session cookie is updated each time the |
|---|
| 263 |
session cookie is sent. |
|---|
| 264 |
|
|---|
| 265 |
Browser-length sessions vs. persistent sessions |
|---|
| 266 |
=============================================== |
|---|
| 267 |
|
|---|
| 268 |
You can control whether the session framework uses browser-length sessions vs. |
|---|
| 269 |
persistent sessions with the ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` setting. |
|---|
| 270 |
|
|---|
| 271 |
By default, ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` is set to ``False``, which |
|---|
| 272 |
means session cookies will be stored in users' browsers for as long as |
|---|
| 273 |
``SESSION_COOKIE_AGE``. Use this if you don't want people to have to log in |
|---|
| 274 |
every time they open a browser. |
|---|
| 275 |
|
|---|
| 276 |
If ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` is set to ``True``, Django will use |
|---|
| 277 |
browser-length cookies -- cookies that expire as soon as the user closes his or |
|---|
| 278 |
her browser. Use this if you want people to have to log in every time they open |
|---|
| 279 |
a browser. |
|---|
| 280 |
|
|---|
| 281 |
Clearing the session table |
|---|
| 282 |
========================== |
|---|
| 283 |
|
|---|
| 284 |
Note that session data can accumulate in the ``django_session`` database table |
|---|
| 285 |
and Django does *not* provide automatic purging. Therefore, it's your job to |
|---|
| 286 |
purge expired sessions on a regular basis. |
|---|
| 287 |
|
|---|
| 288 |
To understand this problem, consider what happens when a user uses a session. |
|---|
| 289 |
When a user logs in, Django adds a row to the ``django_session`` database |
|---|
| 290 |
table. Django updates this row each time the session data changes. If the user |
|---|
| 291 |
logs out manually, Django deletes the row. But if the user does *not* log out, |
|---|
| 292 |
the row never gets deleted. |
|---|
| 293 |
|
|---|
| 294 |
Django provides a sample clean-up script in ``django/bin/daily_cleanup.py``. |
|---|
| 295 |
That script deletes any session in the session table whose ``expire_date`` is |
|---|
| 296 |
in the past -- but your application may have different requirements. |
|---|
| 297 |
|
|---|
| 298 |
Settings |
|---|
| 299 |
======== |
|---|
| 300 |
|
|---|
| 301 |
A few `Django settings`_ give you control over session behavior: |
|---|
| 302 |
|
|---|
| 303 |
SESSION_ENGINE |
|---|
| 304 |
-------------- |
|---|
| 305 |
|
|---|
| 306 |
**New in Django development version** |
|---|
| 307 |
|
|---|
| 308 |
Default: ``django.contrib.sessions.backends.db`` |
|---|
| 309 |
|
|---|
| 310 |
Controls where Django stores session data. Valid values are: |
|---|
| 311 |
|
|---|
| 312 |
* ``'django.contrib.sessions.backends.db'`` |
|---|
| 313 |
* ``'django.contrib.sessions.backends.file'`` |
|---|
| 314 |
* ``'django.contrib.sessions.backends.cache'`` |
|---|
| 315 |
|
|---|
| 316 |
See `configuring the session engine`_ for more details. |
|---|
| 317 |
|
|---|
| 318 |
SESSION_FILE_PATH |
|---|
| 319 |
----------------- |
|---|
| 320 |
|
|---|
| 321 |
**New in Django development version** |
|---|
| 322 |
|
|---|
| 323 |
Default: ``/tmp/`` |
|---|
| 324 |
|
|---|
| 325 |
If you're using file-based session storage, this sets the directory in |
|---|
| 326 |
which Django will store session data. |
|---|
| 327 |
|
|---|
| 328 |
SESSION_COOKIE_AGE |
|---|
| 329 |
------------------ |
|---|
| 330 |
|
|---|
| 331 |
Default: ``1209600`` (2 weeks, in seconds) |
|---|
| 332 |
|
|---|
| 333 |
The age of session cookies, in seconds. |
|---|
| 334 |
|
|---|
| 335 |
SESSION_COOKIE_DOMAIN |
|---|
| 336 |
--------------------- |
|---|
| 337 |
|
|---|
| 338 |
Default: ``None`` |
|---|
| 339 |
|
|---|
| 340 |
The domain to use for session cookies. Set this to a string such as |
|---|
| 341 |
``".lawrence.com"`` for cross-domain cookies, or use ``None`` for a standard |
|---|
| 342 |
domain cookie. |
|---|
| 343 |
|
|---|
| 344 |
SESSION_COOKIE_NAME |
|---|
| 345 |
------------------- |
|---|
| 346 |
|
|---|
| 347 |
Default: ``'sessionid'`` |
|---|
| 348 |
|
|---|
| 349 |
The name of the cookie to use for sessions. This can be whatever you want. |
|---|
| 350 |
|
|---|
| 351 |
SESSION_COOKIE_SECURE |
|---|
| 352 |
--------------------- |
|---|
| 353 |
|
|---|
| 354 |
Default: ``False`` |
|---|
| 355 |
|
|---|
| 356 |
Whether to use a secure cookie for the session cookie. If this is set to |
|---|
| 357 |
``True``, the cookie will be marked as "secure," which means browsers may |
|---|
| 358 |
ensure that the cookie is only sent under an HTTPS connection. |
|---|
| 359 |
|
|---|
| 360 |
SESSION_EXPIRE_AT_BROWSER_CLOSE |
|---|
| 361 |
------------------------------- |
|---|
| 362 |
|
|---|
| 363 |
Default: ``False`` |
|---|
| 364 |
|
|---|
| 365 |
Whether to expire the session when the user closes his or her browser. See |
|---|
| 366 |
"Browser-length sessions vs. persistent sessions" above. |
|---|
| 367 |
|
|---|
| 368 |
SESSION_SAVE_EVERY_REQUEST |
|---|
| 369 |
-------------------------- |
|---|
| 370 |
|
|---|
| 371 |
Default: ``False`` |
|---|
| 372 |
|
|---|
| 373 |
Whether to save the session data on every request. If this is ``False`` |
|---|
| 374 |
(default), then the session data will only be saved if it has been modified -- |
|---|
| 375 |
that is, if any of its dictionary values have been assigned or deleted. |
|---|
| 376 |
|
|---|
| 377 |
.. _Django settings: ../settings/ |
|---|
| 378 |
|
|---|
| 379 |
Technical details |
|---|
| 380 |
================= |
|---|
| 381 |
|
|---|
| 382 |
* The session dictionary should accept any pickleable Python object. See |
|---|
| 383 |
`the pickle module`_ for more information. |
|---|
| 384 |
|
|---|
| 385 |
* Session data is stored in a database table named ``django_session`` . |
|---|
| 386 |
|
|---|
| 387 |
* Django only sends a cookie if it needs to. If you don't set any session |
|---|
| 388 |
data, it won't send a session cookie. |
|---|
| 389 |
|
|---|
| 390 |
.. _`the pickle module`: http://www.python.org/doc/current/lib/module-pickle.html |
|---|
| 391 |
|
|---|
| 392 |
Session IDs in URLs |
|---|
| 393 |
=================== |
|---|
| 394 |
|
|---|
| 395 |
The Django sessions framework is entirely, and solely, cookie-based. It does |
|---|
| 396 |
not fall back to putting session IDs in URLs as a last resort, as PHP does. |
|---|
| 397 |
This is an intentional design decision. Not only does that behavior make URLs |
|---|
| 398 |
ugly, it makes your site vulnerable to session-ID theft via the "Referer" |
|---|
| 399 |
header. |
|---|