Skip to content
Newer
Older
100644 57 lines (40 sloc) 1.83 KB
ae59485 @anandology edit
anandology authored
1 ---
2 layout: default
3 title: Sessions
4 ---
5
6 # Sessions
7
8 ### Problem
9
10 How to use sessions in web.py.
11
3cdb40d edit
shwouchk authored
12 ### Solution - 0.3 Only!
ae59485 @anandology edit
anandology authored
13
22f4ce4 @anandology edit
anandology authored
14 *sessions doesn't work in debug mode because it interfere with reloading. see [session_with_reloader](/session_with_reloader) for more details.*
15
ae59485 @anandology edit
anandology authored
16 The `web.session` module provides session support. Here is a simple application to count using sessions.
17
18 import web
a7173e5 @brentp turn off debugging for session example
brentp authored
19 web.config.debug = False
ae59485 @anandology edit
anandology authored
20 urls = (
21 "/count", "count",
22 "/reset", "reset"
23 )
24 app = web.application(urls, locals())
25 session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'count': 0})
26
27 class count:
28 def GET(self):
29 session.count += 1
30 return str(session.count)
31
32 class reset:
33 def GET(self):
34 session.kill()
35 return ""
36
37 if __name__ == "__main__":
38 app.run()
39
a7173e5 @brentp turn off debugging for session example
brentp authored
40 The session object is loaded with the session data before handling the request and saves the session data after handling the request, if modified. Note in the current (11-22-2008) version of web.py, one must turn off debug to use the development server with sessions.
ae59485 @anandology edit
anandology authored
41
42 The optional `initializer` argument to Session specifies the initial session.
43
cd4b331 @anandology explain DBStore
anandology authored
44 You can use `DBStore` instead of `DiskStore` if you prefer to store sessions in database instead of disk. For using DBStore you need to have a table with the following schema.
ae59485 @anandology edit
anandology authored
45
cd4b331 @anandology explain DBStore
anandology authored
46 create table sessions (
47 session_id char(128) UNIQUE NOT NULL,
dc4d829 @jeffreyhsu edit
jeffreyhsu authored
48 atime timestamp NOT NULL default current_timestamp,
cd4b331 @anandology explain DBStore
anandology authored
49 data text
50 );
51
52 And you need to pass `db` object and session table name to the constructor of `DBStore`.
53
54 db = web.database(dbn='postgres', db='mydatabase', user='myname', pw='')
3eff334 @anandology edit
anandology authored
55 store = web.session.DBStore(db, 'sessions')
cd4b331 @anandology explain DBStore
anandology authored
56 session = web.session.Session(app, store, initializer={'count': 0})
Something went wrong with that request. Please try again.