使用mongodb来实现web.py的session

from web.session import Store
import time

class 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 s

    def __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操作相当于内存操作了。




已有 2 人发表留言,猛击->>这里<<-参与讨论


JavaEye推荐



转载于:https://my.oschina.net/jamiesun/blog/5133

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值