[mod_python] Session.Session(req) not finding saved session

Jim Gallacher jpg at jgassociates.ca
Tue May 1 15:06:02 EDT 2007

Will Gray wrote:
> I'm running Apache 2.2.3 and Mod_Python 3.2.10.  I'm using
> Mod_Python.Publisher to handle requests.  When I upgraded Apache from 
> 2.0 to
> 2.2 (and Mod_Python, accordingly), I was no longer able to get the saved
> session when a visitor changes pages.  Instead, it creates and returns a 
> new
> session.  I was able to verify that the session was still available and
> being saved correctly with the data inside.  Here is a sample of what my
> views are doing:
> def login(req):
>    sess = Session.Session(req)
>    userid = sess.get('uid', None)
>    if userid:
>        util.redirect(req, 'view')
>    ##get username and password from req.form and authenticate against db##
>    if uid:
>        sess['uid'] = uid
>        sess.save()
>        util.redirect(req, 'view')
>    else:
>        ##display the login form##
> def view(req):
>    sess = Session.Session(req) # creates a new session instead of finding
> the old one
>    userid = sess.get('uid', None)
>    if not userid:
>        util.redirect(req, 'login')
>    ##do some db queries and display the page##

I don't see an immediate problem with the code snippet, but given the 
redirecting back and forth I think the potential is there for things to 
get out of order.

Try tracing through your execution path again and make sure the session 
is indeed being saved at the appropriate time.

Also remember that your session instance must be created *before* 
returning any output to the client. The first call to req.write() 
flushes the response headers. Once that happens it's too late to create 
the session object - you can still create it and save it, but the 
session cookie will not be sent to the client, so you'll end up with at 
new session for every request. Typically this results in the behaviour 
you are seeing - the session data gets saved, but you always end up with 
a new session.


More information about the Mod_python mailing list