Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 55 lines (39 sloc) 1.724 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
14 The `web.session` module provides session support. Here is a simple application to count using sessions.
15
16 import web
a7173e5 @brentp turn off debugging for session example
brentp authored
17 web.config.debug = False
ae59485 @anandology edit
anandology authored
18 urls = (
19 "/count", "count",
20 "/reset", "reset"
21 )
22 app = web.application(urls, locals())
23 session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'count': 0})
24
25 class count:
26 def GET(self):
27 session.count += 1
28 return str(session.count)
29
30 class reset:
31 def GET(self):
32 session.kill()
33 return ""
34
35 if __name__ == "__main__":
36 app.run()
37
a7173e5 @brentp turn off debugging for session example
brentp authored
38 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
39
40 The optional `initializer` argument to Session specifies the initial session.
41
cd4b331 @anandology explain DBStore
anandology authored
42 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
43
cd4b331 @anandology explain DBStore
anandology authored
44 create table sessions (
45 session_id char(128) UNIQUE NOT NULL,
dc4d829 @jeffreyhsu edit
jeffreyhsu authored
46 atime timestamp NOT NULL default current_timestamp,
cd4b331 @anandology explain DBStore
anandology authored
47 data text
48 );
49
50 And you need to pass `db` object and session table name to the constructor of `DBStore`.
51
52 db = web.database(dbn='postgres', db='mydatabase', user='myname', pw='')
3eff334 @anandology edit
anandology authored
53 store = web.session.DBStore(db, 'sessions')
cd4b331 @anandology explain DBStore
anandology authored
54 session = web.session.Session(app, store, initializer={'count': 0})
Something went wrong with that request. Please try again.