Python 提前初始化cherrypy.session

Python 提前初始化cherrypy.session,python,cherrypy,Python,Cherrypy,我喜欢CherryPy的会话API,除了一个细节。我不想说cherrypy.session[“spam”]我只想说session[“spam”] 不幸的是,我不能简单地在我的一个模块中有一个全局from cherrypy import session,因为直到第一次发出页面请求时才创建cherrypy.session对象。有没有办法让CherryPy立即初始化其会话对象,而不是在第一个页面请求上初始化 如果答案是否定的,我有两个丑陋的选择: 首先,我可以这样做 def import_sessio

我喜欢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


所以我更喜欢一种简单的方法来初始化对象。有人知道怎么做吗?

对于CherryPy 3.1,您需要找到会话的正确子类,运行其“setup”classmethod,然后将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):

“kwargs”由“timeout”、“clean_freq”和tools.sessions.*config中任何子类特定的条目组成

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