Django

Code

root/django/branches/new-admin/docs/sessions.txt

Revision 1309, 8.8 kB (checked in by rjwittams, 3 years ago)

Merge to trunk r1307

Line 
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 Session functionality is enabled by default.
14
15 You can turn session functionality on and off by editing the
16 ``MIDDLEWARE_CLASSES`` setting. To activate sessions, make sure
17 ``MIDDLEWARE_CLASSES`` contains ``"django.middleware.sessions.SessionMiddleware"``.
18
19 If you're dealing with an admin site, make sure the ``SessionMiddleware`` line
20 appears before the ``AdminUserRequired`` line. (The middleware classes are
21 applied in order, and the admin middleware requires that the session middleware
22 come first.)
23
24 If you don't want to use sessions, you might as well remove the
25 ``SessionMiddleware`` line from ``MIDDLEWARE_CLASSES``. It'll save you a small
26 bit of overhead.
27
28 Using sessions in views
29 =======================
30
31 Each ``HttpRequest`` object -- the first argument to any Django view function --
32 has a ``session`` attribute, which is a dictionary-like object. You can read
33 it and write to it.
34
35 It implements the following standard dictionary methods:
36
37     * ``__getitem__(key)``
38       Example: ``fav_color = request.session['fav_color']``
39
40     * ``__setitem__(key, value)``
41       Example: ``request.session['fav_color'] = 'blue'``
42
43     * ``__delitem__(key)``
44       Example: ``del request.session['fav_color']``. This raises ``KeyError``
45       if the given ``key`` isn't already in the session.
46
47     * ``get(key, default=None)``
48       Example: ``fav_color = request.session.get('fav_color', 'red')``
49
50 It also has these three methods:
51
52     * ``set_test_cookie()``
53       Sets a test cookie to determine whether the user's browser supports
54       cookies. Due to the way cookies work, you won't be able to test this
55       until the user's next page request. See "Setting test cookies" below for
56       more information.
57
58     * ``test_cookie_worked()``
59       Returns either ``True`` or ``False``, depending on whether the user's
60       browser accepted the test cookie. Due to the way cookies work, you'll
61       have to call ``set_test_cookie()`` on a previous, separate page request.
62       See "Setting test cookies" below for more information.
63
64     * ``delete_test_cookie()``
65       Deletes the test cookie. Use this to clean up after yourself.
66
67 You can edit ``request.session`` at any point in your view. You can edit it
68 multiple times.
69
70 Session object guidelines
71 -------------------------
72
73     * Use normal Python strings as dictionary keys on ``request.session``. This
74       is more of a convention than a hard-and-fast rule.
75
76     * Session dictionary keys that begin with an underscore are reserved for
77       internal use by Django.
78
79     * Don't override ``request.session`` with a new object, and don't access or
80       set its attributes. Use it like a Python dictionary.
81
82 Examples
83 --------
84
85 This simplistic view sets a ``has_commented`` variable to ``True`` after a user
86 posts a comment. It doesn't let a user post a comment more than once::
87
88     def post_comment(request, new_comment):
89         if request.session.get('has_commented', False):
90             return HttpResponse("You've already commented.")
91         c = comments.Comment(comment=new_comment)
92         c.save()
93         request.session['has_commented'] = True
94         return HttpResponse('Thanks for your comment!')
95
96 This simplistic view logs in a "member" of the site::
97
98     def login(request):
99         m = members.get_object(username__exact=request.POST['username'])
100         if m.password == request.POST['password']:
101             request.session['member_id'] = m.id
102             return HttpResponse("You're logged in.")
103         else:
104             return HttpResponse("Your username and password didn't match.")
105
106 ...And this one logs a member out, according to ``login()`` above::
107
108     def logout(request):
109         try:
110             del request.session['member_id']
111         except KeyError:
112             pass
113         return HttpResponse("You're logged out.")
114
115 Setting test cookies
116 ====================
117
118 As a convenience, Django provides an easy way to test whether the user's
119 browser accepts cookies. Just call ``request.session.set_test_cookie()`` in a
120 view, and call ``request.session.test_cookie_worked()`` in a subsequent view --
121 not in the same view call.
122
123 This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()``
124 is necessary due to the way cookies work. When you set a cookie, you can't
125 actually tell whether a browser accepted it until the browser's next request.
126
127 It's good practice to use ``delete_test_cookie()`` to clean up after yourself.
128 Do this after you've verified that the test cookie worked.
129
130 Here's a typical usage example::
131
132     def login(request):
133         if request.POST:
134             if request.session.test_cookie_worked():
135                 request.session.delete_test_cookie()
136                 return HttpResponse("You're logged in.")
137             else:
138                 return HttpResponse("Please enable cookies and try again.")
139         request.session.set_test_cookie()
140         return render_to_response('foo/login_form')
141
142 Using sessions out of views
143 ===========================
144
145 Internally, each session is just a normal Django model. The ``Session`` model
146 is defined in ``django/models/core.py``. Because it's a normal model, you can
147 access sessions using the normal Django database API::
148
149     >>> from django.models.core import sessions
150     >>> s = sessions.get_object(pk='2b1189a188b44ad18c35e113ac6ceead')
151     >>> s.expire_date
152     datetime.datetime(2005, 8, 20, 13, 35, 12)
153
154 Note that you'll need to call ``get_decoded()`` to get the session dictionary.
155 This is necessary because the dictionary is stored in an encoded format::
156
157     >>> s.session_data
158     'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
159     >>> s.get_decoded()
160     {'user_id': 42}
161
162 When sessions are saved
163 =======================
164
165 By default, Django only saves to the session database when the session has been
166 modified -- that is if any of its dictionary values have been assigned or
167 deleted::
168
169     # Session is modified.
170     request.session['foo'] = 'bar'
171
172     # Session is modified.
173     del request.session['foo']
174
175     # Session is modified.
176     request.session['foo'] = {}
177
178     # Gotcha: Session is NOT modified, because this alters
179     # request.session['foo'] instead of request.session.
180     request.session['foo']['bar'] = 'baz'
181
182 **Only available in Django development version.** To change this default
183 behavior, set the ``SESSION_SAVE_EVERY_REQUEST`` setting  to ``True``. If
184 ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, Django will save the session to the
185 database on every single request.
186
187 Note that the session cookie is only sent when a session has been created or
188 modified. If ``SESSION_SAVE_EVERY_REQUEST`` is ``True``, the session cookie
189 will be sent on every request.
190
191 Similarly, the ``expires`` part of a session cookie is updated each time the
192 session cookie is sent.
193
194 Settings
195 ========
196
197 A few `Django settings`_ give you control over session behavior:
198
199 SESSION_COOKIE_AGE
200 ------------------
201
202 Default: ``1209600`` (2 weeks, in seconds)
203
204 The age of session cookies, in seconds.
205
206 SESSION_COOKIE_DOMAIN
207 ---------------------
208
209 Default: ``None``
210
211 The domain to use for session cookies. Set this to a string such as
212 ``".lawrence.com"`` for cross-domain cookies, or use ``None`` for a standard
213 domain cookie.
214
215 SESSION_COOKIE_NAME
216 -------------------
217
218 Default: ``'hotclub'``
219
220 The name of the cookie to use for sessions. This can be whatever you want.
221
222 ``'hotclub'`` is a reference to the Hot Club of France, the band Django
223 Reinhardt played in.
224
225 SESSION_SAVE_EVERY_REQUEST
226 --------------------------
227
228 Default: ``False``
229
230 **Only available in Django development version.**
231
232 Whether to save the session data on every request. If this is ``False``
233 (default), then the session data will only be saved if it has been modified --
234 that is, if any of its dictionary values have been assigned or deleted.
235
236 .. _Django settings: http://www.djangoproject.com/documentation/settings/
237
238 Technical details
239 =================
240
241     * The session dictionary should accept any pickleable Python object. See
242       `the pickle module`_ for more information.
243
244     * Session data is stored in a database table named ``core_sessions`` .
245
246     * Django only sends a cookie if it needs to. If you don't set any session
247       data, it won't send a session cookie.
248
249 .. _`the pickle module`: http://www.python.org/doc/current/lib/module-pickle.html
250
251 Session IDs in URLs
252 ===================
253
254 The Django sessions framework is entirely, and solely, cookie-based. It does
255 not fall back to putting session IDs in URLs as a last resort, as PHP does.
256 This is an intentional design decision. Not only does that behavior make URLs
257 ugly, it makes your site vulnerable to session-ID theft via the "Referer"
258 header.
Note: See TracBrowser for help on using the browser.