Django

Code

root/django/branches/magic-removal/docs/sessions.txt

Revision 2788, 8.8 kB (checked in by adrian, 3 years ago)

magic-removal: Proofread docs/sessions.txt

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