使用 mongodb 来实现 web.py 的 session
from web.session import Store
import timeclass MongoStore(Store):
def __init__(self, db, collection_name):
self.collection = db[collection_name]
def __contains__(self, key):
data = self.collection.find_one({'session_id':key})
return bool(data)def __getitem__(self, key):
now = time.time()
s = self.collection.find_one({'session_id':key})
if not s:
raise KeyError
else:
s.update({'attime':now})
return sdef __setitem__(self, key, value):
now = time.time()value['attime'] = now
s = self.collection.find_one({'session_id':key})
if s:
value = dict(map(lambda x: (str(x[0]), x[1]), [(k,v) for (k,v) in value.iteritems() if k not in ['_id']]))
s.update(**value)
self.collection.save(s)
else:
self.collection.insert(value)
def __delitem__(self, key):
self.collection.remove({'session_id':key})def cleanup(self, timeout):
timeout = timeout/(24.0*60*60) #timedelta takes numdays as arg
last_allowed_time = time.time() - timeout
self.collection.remove({'attime' : { '$lt' : last_allowed_time}})
在你的app中使用
session = web.session.Session(app, MongoStore(db, 'sessions'))
代替
session = web.session.Session(app, web.session.DiskStore('sessions'))
DiskStore是直接进行磁盘io操作的,性能很低,而mongodb操作相当于内存操作了。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。