Search code examples
pythoncherrypy

I am struggling to understand sessions in CherryPy


I recently began a project to migrate our web app from apache + Mod_python to just cherry-py.

There is still a good deal of stuff I still need to do, but for now, it is CherryPy's sessions that are giving me a bit of a headache.

My first question is how do they work?

In Mod_python, we do something like this:

...
from mod_python import Session
sess = Session.Session(req, timeout = 60*60, lock=0)
#req is the request page object.

Judging from the CherryPy documentation, all I need to do to start a session is modify the config by adding something like the following:

cherrypy.config.update({
    'tools.sessions.on': True, 
    'tools.sessions.storage_type': 'ram'})

The above defaults to a time of 60 minutes (though you can manually set your own), but what if I want to destroy that session and make a new one? Do, I call cherrypy.lib.sessions.expire() in any arbitrary file and then do the cherrypy.config.update thing again? Or, will CherryPy make a new session by itself? What if I want to make a new session with a different expiry time?

Note: When I say arbitrary file, I mean a file that is not running CherryPy (My "config" file imports and gets html back from our other pages much like the standard Publisher that comes with Mod_Python).

I tried making a quick little test file:

import cherrypy
from cherrypy.lib import sessions

def index(sid=0, secret=None, timeout=30, lock=1):
    cherrypy.session['test'] = 'test'
    cherrypy.lib.sessions.expire()
    return cherrypy.session.get('test','None')

The end result is that 'test' is still displayed on the screen. Is this happening because the client side session is expired, but the local one still has data? In that case, how can I check if a session expired or not?

Sorry for the confusing question, but I am confused.

Thanks for all your help!


Solution

  • Try this to end a session.

    sess = cherrypy.session
    sess['_cp_username'] = None
    

    and try this to create a session...

    cherrypy.session.regenerate()
    cherrypy.session['_cp_username'] = cherrypy.request.login
    

    I used this example to handle most of my session activity.

    http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions

    Hope this helps,

    Andrew