2008-10-03 71 views
3

我喜歡CherryPy的會話API,除了一個細節。我不想說​​我只想說session["spam"]儘早初始化cherrypy.session

不幸的是,我不能簡單地在我的模塊中有一個全局的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() 

這感覺就像一個大的雜牌,但我真的很討厭寫​​每一次,所以對我來說這是值得的。

我的第二個解決辦法是做類似

class SessionKludge: 
    def __getitem__(self, name): 
     return cherrypy.session[name] 
    def __setitem__(self, name, val): 
     cherrypy.session[name] = val 

session = SessionKludge() 

但這種感覺就像一個更大的組裝機和我需要做更多的工作來實現其他詞典功能,如.get

所以我肯定會更喜歡簡單的方法來自己初始化對象。有誰知道如何做到這一點?

回答

5

對於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') 

減少(你想要的子類替換FileSession):

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

的 「kwargs」 包括「超時「,」clean_freq「以及tools.sessions。* config中的所有子類特定條目。