使用MongoDB来实现web.py的session存储

web.py 是一个python的web开发框架,既然涉及到web开发,那么不可避免的可能使用到session,而传统的session存储基本都是默认在磁盘,当然考虑到web前端机的扩展我们经常需要重写session handler来自定义session的存储。下面就是在web.py框架中使用MongoDB作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'))

来源:python.cn

anyShare赠人玫瑰,手有余香,分享知识,德艺双馨!
          

无觅相关文章插件,快速提升流量

分类 MongoDB · tag , ,