果壳网

科技-新知-智趣,很新税的科技主题网站,用 Django 做的,重构使用 Flask ...

↑我也要推荐

Flask 0.7 扩展自己的 session 模块方法 by @上晴

发布时间:2011-08-18 22:34:45, 关注:+7515, 赞美:+10, 不爽:+9

本文标签: session

原始出处: 上晴的博客

#如果你想在flask 0.7中支持自定义的seesion扩展,session接口在 flask 0.8中提供支持,
#0.7版本要实现要自己写一段胶水代码
#具体说明官方地址:http://flask.pocoo.org/snippets/52/
try:
    from flask.sessions import SessionMixin, SessionInterface
except ImportError:
    class SessionInterface(object):
        pass

    class SessionMixin(object):
        def _get_permanent(self):
            return self.get('_permanent', False)
        def _set_permanent(self, value):
            self['_permanent'] = bool(value)
        permanent = property(_get_permanent, _set_permanent)
        del _get_permanent, _set_permanent

        # you can use a werkzeug.datastructure.CallbackDict
        # to automatically update modified if you want, but
        # it's not a requirement.
        new = False
        modified = True


class MySession(dict, SessionMixin):
     pass


class MySessionInterface(object):

    def open_session(self, app, request):
        # load the session and return it.
        return MySession()

    def save_session(self, app, session, response):
        # save the session
        ...


def init_my_extension(app):
    if not hasattr(app, 'session_interface'):
        app.open_session = lambda r: \
            app.session_interface.open_session(app, r)
        app.save_session = lambda s, r: \
            app.session_interface.save_session(app, s, r)
    app.session_interface = MySessionInterface()

如果你觉得本站对你有帮助,欢迎向本站赞助 :P

使用支付宝捐赠

Copyright© Python4cn(news, jobs) simple-is-better.com, 技术驱动:powered by web.py 空间主机:Webfaction

版权申明:文章转载已注明出处,如有疑问请来信咨询。本站为 python 语言推广公益网站,与 python 官方没有任何关系。

联系/投搞/留言: en.simple.is.better@gmail.com 向本站捐赠