python实现session

Python实现Session存储方式
本文介绍了两种Python中实现Session的方法,一种是将Session保存在磁盘上,另一种是存储在MySQL数据库中。通过示例代码详细展示了如何配置和使用这两种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>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值