首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >提前初始化cherrypy.session

提前初始化cherrypy.session
EN

Stack Overflow用户
提问于 2008-10-03 18:16:09
回答 1查看 2.4K关注 0票数 3

我喜欢CherryPy的会话API,除了一个细节。我想只说session["spam"],而不是cherrypy.session["spam"]

不幸的是,我不能简单地在我的一个模块中拥有一个全局from cherrypy import session,因为直到第一次发出页面请求时才创建cherrypy.session对象。有没有办法让CherryPy立即初始化它的session对象,而不是在第一个页面请求时初始化?

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

首先,我可以这样做

代码语言:javascript
复制
def import_session():
    global session
    while not hasattr(cherrypy, "session"):
        sleep(0.1)
    session = cherrypy.session

Thread(target=import_session).start()

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

我的第二个解决方案是这样做

代码语言:javascript
复制
class SessionKludge:
    def __getitem__(self, name):
        return cherrypy.session[name]
    def __setitem__(self, name, val):
        cherrypy.session[name] = val

session = SessionKludge()

但这感觉像是一个更大的杂凑,我需要做更多的工作来实现其他字典函数,如.get

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2008-10-04 05:12:53

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

代码语言:javascript
复制
# 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')

Reducing (将FileSession替换为所需的子类):

代码语言:javascript
复制
FileSession.setup(**kwargs)
cherrypy.session = cherrypy._ThreadLocalProxy('session')

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/168167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档