除了一个细节,我喜欢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()
Run Code Online (Sandbox Code Playgroud)
这感觉就像一个大块头,但我真的很讨厌cherrypy.session["spam"]每次写作,所以对我来说这是值得的.
我的第二个解决方案是做类似的事情
class SessionKludge:
def __getitem__(self, name):
return cherrypy.session[name]
def __setitem__(self, name, val):
cherrypy.session[name] = val
session = SessionKludge()
Run Code Online (Sandbox Code Playgroud)
但这感觉就像一个更大的kludge,我需要做更多的工作来实现其他字典功能,如 .get
所以我绝对更喜欢一种简单的方法来自己初始化对象.有谁知道如何做到这一点?
对于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')
Run Code Online (Sandbox Code Playgroud)
减少(用你想要的子类替换FileSession):
FileSession.setup(**kwargs)
cherrypy.session = cherrypy._ThreadLocalProxy('session')
Run Code Online (Sandbox Code Playgroud)
"kwargs"由"timeout","clean_freq"以及tools.sessions.*config中任何特定于子类的条目组成.