提前初始化 cherrypy.session

3 投票
1 回答
2478 浏览
提问于 2025-04-11 09:26

我很喜欢CherryPy的会话API,除了一个小细节。 我希望能直接使用 session["spam"],而不是 cherrypy.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

所以我肯定更希望能有一个简单的方法来自己初始化这个对象。 有人知道怎么做吗?

1 个回答

5

对于CherryPy 3.1,你需要找到Session的正确子类,运行它的'setup'类方法,然后将cherrypy.session设置为一个线程本地代理。这些操作都在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”(清理频率)以及任何特定于子类的工具.sessions.*配置项。

撰写回答