Django

Code

root/django/branches/0.90-bugfixes/docs/sessions.txt

Revision 1211, 7.4 kB (checked in by adrian, 3 years ago)

Changed slightly misleading example in docs/sessions.txt to use baggage-less 'members' instead of 'users'

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']``
45
46     * ``get(key, default=None)``
47       Example: ``fav_color = request.session.get('fav_color', 'red')``
48
49 It also has these three methods:
50
51     * ``set_test_cookie()``
52       Sets a test cookie to determine whether the user's browser supports
53       cookies. Due to the way cookies work, you won't be able to test this
54       until the user's next page request. See "Setting test cookies" below for
55       more information.
56
57     * ``test_cookie_worked()``
58       Returns either ``True`` or ``False``, depending on whether the user's
59       browser accepted the test cookie. Due to the way cookies work, you'll
60       have to call ``set_test_cookie()`` on a previous, separate page request.
61       See "Setting test cookies" below for more information.
62
63     * ``delete_test_cookie()``
64       Deletes the test cookie. Use this to clean up after yourself.
65
66 You can edit ``request.session`` at any point in your view. You can edit it
67 multiple times.
68
69 Session object guidelines
70 -------------------------
71
72     * Use normal Python strings as dictionary keys on ``request.session``. This
73       is more of a convention than a hard-and-fast rule.
74
75     * Session dictionary keys that begin with an underscore are reserved for
76       internal use by Django.
77
78     * Don't override ``request.session`` with a new object, and don't access or
79       set its attributes. Use it like a Python dictionary.
80
81 Examples
82 --------
83
84 This simplistic view sets a ``has_commented`` variable to ``True`` after a user
85 posts a comment. It doesn't let a user post a comment more than once::
86
87     def post_comment(request, new_comment):
88         if request.session.get('has_commented', False):
89             return HttpResponse("You've already commented.")
90         c = comments.Comment(comment=new_comment)
91         c.save()
92         request.session['has_commented'] = True
93         return HttpResponse('Thanks for your comment!')
94
95 This simplistic view logs in a "member" of the site::
96
97     def login(request):
98         m = members.get_object(username__exact=request.POST['username'])
99         if m.password == request.POST['password']:
100             request.session['member_id'] = m.id
101             return HttpResponse("You're logged in.")
102         else:
103             return HttpResponse("Your username and password didn't match.")
104
105 ...And this one logs a member out, according to ``login()`` above::
106
107     def logout(request):
108         try:
109             del request.session['member_id']
110         except KeyError:
111             pass
112         return HttpResponse("You're logged out.")
113
114 Setting test cookies
115 ====================
116
117 As a convenience, Django provides an easy way to test whether the user's
118 browser accepts cookies. Just call ``request.session.set_test_cookie()`` in a
119 view, and call ``request.session.test_cookie_worked()`` in a subsequent view --
120 not in the same view call.
121
122 This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()``
123 is necessary due to the way cookies work. When you set a cookie, you can't
124 actually tell whether a browser accepted it until the browser's next request.
125
126 It's good practice to use ``delete_test_cookie()`` to clean up after yourself.
127 Do this after you've verified that the test cookie worked.
128
129 Here's a typical usage example::
130
131     def login(request):
132         if request.POST:
133             if request.session.test_cookie_worked():
134                 request.session.delete_test_cookie()
135                 return HttpResponse("You're logged in.")
136             else:
137                 return HttpResponse("Please enable cookies and try again.")
138         request.session.set_test_cookie()
139         return render_to_response('foo/login_form')
140
141 Using sessions out of views
142 ===========================
143
144 Internally, each session is just a normal Django model. The ``Session`` model
145 is defined in ``django/models/core.py``. Because it's a normal model, you can
146 access sessions using the normal Django database API::
147
148     >>> from django.models.core import sessions
149     >>> s = sessions.get_object(pk='2b1189a188b44ad18c35e113ac6ceead')
150     >>> s.expire_date
151     datetime.datetime(2005, 8, 20, 13, 35, 12)
152
153 Note that you'll need to call ``get_decoded()`` to get the session dictionary.
154 This is necessary because the dictionary is stored in an encoded format::
155
156     >>> s.session_data
157     'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
158     >>> s.get_decoded()
159     {'user_id': 42}
160
161 Session cookies
162 ===============
163
164 A few `Django settings`_ give you control over the session cookie:
165
166 SESSION_COOKIE_AGE
167 ------------------
168
169 Default: ``1209600`` (2 weeks, in seconds)
170
171 The age of session cookies, in seconds.
172
173 SESSION_COOKIE_DOMAIN
174 ---------------------
175
176 Default: ``None``
177
178 The domain to use for session cookies. Set this to a string such as
179 ``".lawrence.com"`` for cross-domain cookies, or use ``None`` for a standard
180 domain cookie.
181
182 SESSION_COOKIE_NAME
183 -------------------
184
185 Default: ``'hotclub'``
186
187 The name of the cookie to use for sessions. This can be whatever you want.
188
189 ``'hotclub'`` is a reference to the Hot Club of France, the band Django
190 Reinhardt played in.
191
192 .. _Django settings: http://www.djangoproject.com/documentation/settings/
193
194 Technical details
195 =================
196
197     * The session dictionary should accept any pickleable Python object. See
198       `the pickle module`_ for more information.
199
200     * Session data is stored in a database table named ``core_sessions`` .
201
202     * Django only sends a cookie if it needs to. If you don't set any session
203       data, it won't send a session cookie.
204
205 .. _`the pickle module`: http://www.python.org/doc/current/lib/module-pickle.html
206
207 Session IDs in URLs
208 ===================
209
210 The Django sessions framework is entirely, and solely, cookie-based. It does
211 not fall back to putting session IDs in URLs as a last resort, as PHP does.
212 This is an intentional design decision. Not only does that behavior make URLs
213 ugly, it makes your site vulnerable to session-ID theft via the "Referer"
214 header.
Note: See TracBrowser for help on using the browser.