我喜欢CherryPy的会话API,除了一个细节。我想只说session["spam"]
,而不是cherrypy.session["spam"]
。
不幸的是,我不能简单地在我的一个模块中拥有一个全局from cherrypy import session
,因为直到第一次发出页面请求时才创建cherrypy.session
对象。有没有办法让CherryPy立即初始化它的session对象,而不是在第一个页面请求时初始化?
如果答案是否定的,我有两个丑陋的选择:
首先,我可以这样做
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
所以我更喜欢一种简单的方法来自己初始化对象。有人知道怎么做吗?
发布于 2008-10-04 05:12:53
对于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')
Reducing (将FileSession替换为所需的子类):
FileSession.setup(**kwargs)
cherrypy.session = cherrypy._ThreadLocalProxy('session')
"kwargs“由"timeout”、"clean_freq“和来自tools.sessions.* config的任何特定于子类的条目组成。
https://stackoverflow.com/questions/168167
复制相似问题