[mod_python] The right way to handle sessions

Byron Ellacott bje at apnic.net
Thu Aug 19 10:03:11 EDT 2004


Amir Salihefendic wrote:
>> def createSession(req):
>> def getSameSession(req, SID):
> Argh forgot something very important (to save the damn session)!:
>> Anyway, I am interested in knowing: What is the smartest way to 
>> "share"/access same session across functions (i.e. when you are 
>> internal "redirecting")? Example of what I mean by "redirecting" (not 
>> working...):

In case saving the session in createSession() didn't solve your problem, 
I'd suggest collapsing the two functions into one, since you don't seem 
to really need to distinguish between creating a session and fetching an 
existing one, as demonstrated by your getSameSession() function not 
checking if the session it fetches is newly created:

def getSession(req):
     sess = Session.Session(req)
     if sess.is_new(): sess.save()
     return sess

Of course, you now have the problem that the session might have already 
been created during the processing of this request.  I'm not very 
familiar with the publisher approach, but I'm assuming it calls a method 
based on the requested URL, essentially doing a dispatch for you.  This 
is awkward when you want to have functions done outside of the 
dispatched routine, but you can alter getSession() to help out:

def getSession(req):
     if not hasattr(req, 'session'):
         req.session = Session.Session(req)
         if req.session.is_new(): req.session.save()
     return req.session

You can assign to attributes of a request object, and those attributes 
will last for the lifetime of the request (but not cross-interpreter, so 
be careful about request phases and which configuration directives apply 
when, if you do multi-phase handlers!).  So, you can cache the previous 
getSession() request in the req object itself.

Of course, if your problem is solved, there's not a great deal of point 
in doing this anyway, and storing attributes in the request object is 
probably about as unclean as calling session.unlock() to allow you to 
fetch a session twice.

-- 
bje


More information about the Mod_python mailing list