【问题标题】:Initializing cherrypy.session early尽早初始化cherrypy.session
【发布时间】:2008-10-03 18:16:08
【问题描述】:

我喜欢 CherryPy 的会话 API,除了一个细节。与其说cherrypy.session["spam"],不如说session["spam"]

不幸的是,我不能简单地在我的一个模块中使用全局 from cherrypy import session,因为直到第一次发出页面请求时才会创建 cherrypy.session 对象。有什么方法可以让 CherryPy 立即初始化其会话对象,而不是在第一页请求上?

如果答案是否定的,我有两个丑陋的选择:

首先,我可以做这样的事情

def import_session():
    global session
    while not hasattr(cherrypy, "session"):
        sleep(0.1)
    session = cherrypy.session

Thread(target=import_session).start()

这感觉像是一个大杂烩,但我真的很讨厌每次都写cherrypy.session["spam"],所以对我来说这是值得的。

我的第二个解决方案是做类似的事情

class SessionKludge:
    def __getitem__(self, name):
        return cherrypy.session[name]
    def __setitem__(self, name, val):
        cherrypy.session[name] = val

session = SessionKludge()

但这感觉像是一个更大的混乱,我需要做更多的工作来实现其他字典功能,例如.get

所以我肯定更喜欢自己初始化对象的简单方法。有人知道怎么做吗?

【问题讨论】:

    标签: python cherrypy


    【解决方案1】:

    对于 CherryPy 3.1,您需要找到 Session 的正确子类,运行它的“setup”类方法,然后将cherrypy.session 设置为 ThreadLocalProxy。这一切都发生在cherrypy.lib.sessions.init 中,在以下块中:

    # Find the storage class and call setup (first time only).
    storage_class = storage_type.title() + 'Session'
    storage_class = globals()[storage_class]
    if not hasattr(cherrypy, "session"):
        if hasattr(storage_class, "setup"):
            storage_class.setup(**kwargs)
    
    # Create cherrypy.session which will proxy to cherrypy.serving.session
    if not hasattr(cherrypy, "session"):
        cherrypy.session = cherrypy._ThreadLocalProxy('session')
    

    减少(用你想要的子类替换 FileSession):

    FileSession.setup(**kwargs)
    cherrypy.session = cherrypy._ThreadLocalProxy('session')
    

    “kwargs”由“timeout”、“clean_freq”和来自 tools.sessions.* 配置的任何子类特定条目组成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多