Initialize cherrypy.session early

I like the CherryPy API for sessions, except for one detail. Instead of talking cherrypy.session["spam"], I would just say session["spam"].

Unfortunately, I cannot just have global from cherrypy import sessionin one of my modules, because the object is cherrypy.sessionnot created until the first page request. Is there a way to get CherryPy to immediately initialize its session object instead of requesting the first page?

I have two ugly alternatives if the answer is no:

Firstly, I can do something like this

def import_session():
    global session
    while not hasattr(cherrypy, "session"):
        sleep(0.1)
    session = cherrypy.session

Thread(target=import_session).start()

It sounds like a big kludge, but I really hate writing cherrypy.session["spam"]every time, so it's worth it for me.

My second solution is to do something like

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

session = SessionKludge()

kludge, , .get

. - , ?

+3
1

CherryPy 3.1 Session, 'setup' classmethod, 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" "timeout", "clean_freq" ​​ , , tools.sessions. * config.

+5

Source: https://habr.com/ru/post/1697873/


All Articles