首页 > 代码库 > python实现session

python实现session

第一种,将浏览器产生的session会话保存在磁盘上的主程序。

#-*- 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. 将session保存在本地磁盘上。
session = web.session.Session(app,web.session.DiskStore(‘sessions‘),
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()


第二种,将浏览器session会话的信息,保存在数据库mysql中。

表结构如下:

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-12-03
@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   将session信息保存在数据库中。
db = web.database(dbn=‘mysql‘,db=‘py‘,user=‘root‘,pw=‘123456‘)
store = web.session.DBStore(db,‘sessions‘)
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()

index.html文件如下:

<!doctype html>
<html>
<head>
<title>test sessions</title>
</head>
<body>
<h1>
<span>
You are logged in as <b> $context.count </b>
</span>
</h1>
</body>
</html>>

python实现session