Python implements session
First, save the session generated by the browser to the master program on the disk.
#-*-Coding: UTF-8 -*-
'''
@ Author: cuiruiqiang
@ Date: 2014-12-3
@ Filename: CountSession. py count session's number
'''
Import web
Web. config. debug = False
Urls = (
'/', 'Index ',
'/Count', 'Count ',
'/Reset', 'reset'
)
App = web. application (urls, locals ())
# Session is be stored on disk. Save the session on the local disk.
Session = web. session. Session (app, web. session. DiskStore ('session '),
Initializer = {'Count': 0 })
Class count:
Def GET (self ):
Session. count + = 1
Return str (session. count)
Class reset:
Def GET (self ):
Session. kill ()
Return ""
If _ name _ = "_ main __":
App. run ()
Second, save the session information of the browser in mysql.
The table structure is as follows:
Create table sessions (
Session_id char (128) unique not null,
Atime timestamp not null default current_timestamp,
Data text)
#-*-Coding: UTF-8 -*-
'''
@ Author: cuiruiqiang
@ Date: 2014-3 3
@ Filename: server. py
'''
Import web
Web. config. debug = False
Urls = (
'/', 'Index ',
'/Count', 'Count ',
'/Reset', 'reset'
)
App = web. application (urls, locals ())
# Session is be stored database stores session information in the database.
Db = web. database (dbn = 'mysql', db = 'py', user = 'root', pw = '123 ')
Store = web. session. DBStore (db, 'session ')
Session = web. session. Session (app, store, initializer = {'Count': 0 })
Render = web. template. render ('template/', globals = {'context': session })
Class index:
Def GET (self ):
Return render. index ()
Class count:
Def GET (self ):
Session. count + = 1
Return str (session. count)
Class reset:
Def GET (self ):
Session. kill ()
Return ""
If _ name _ = "_ main __":
App. run ()
The index.html file is as follows:
Test sessions
You are logged in$ Context. count
>