[mod_python] The right way to handle sessions

Amir Salihefendic amix at amix.dk
Thu Aug 12 15:13:01 EDT 2004


Hello.
I welcome myself to this list ;-)

I have a question about how to handle sessions correctly.
I am creating a simple login system (just messing around with 
mod_python).
Let's say that we have a page called index.py and we are using the 
publisher handler.

Example one:
def createSession(req):
     new_session = Session.Session(req)
     return new_session.id()

def getSameSession(req):
     same_session = Session.Session(req)
     return same_session.id()

This works ok! They have the same sid. I.e. you first call 
index.py/createSession and then  index.py/getSameSession


Example two:
def createSession(req):
     new_session = Session.Session(req)
     return getSameSession(req)

def getSameSession(req):
     same_session = Session.Session(req)
     return same_session.id()

This does not work - it makes an infinitive loop..!  Now to fix this 
you need to unlock the session in createSession (.. I have no clue why 
you have to do this..?). And then you need to restart apache...  i.e.:
def createSession(req):
     new_session = Session.Session(req)
     new_session.unlock()
     return getSameSession(req)

But this does not work quite well.. If you delete the Session:
def deleteSession(req):
     same_session = Session.Session(req)
     same_session.invalidate()
     return "Deleted"

And then you do this:
def createSession(req):
     new_session = Session.Session(req)
     new_session.save()
     new_session.unlock()

     req.write(new_session.id())
     return getSameSession(req)

def getSameSession(req):
     same_session = Session.Session(req)

     return "\n%s" % same_session.id()

First time the id's aren't same - after that they are the same.


Now, I could solve this by doing internal redirects i.e. instead of 
calling "return getSameSession" I could go util.redirect... But that 
isn't smart...

I could also store some variables in the request object. I.e. 
req.login["Logged_in"] = True. i.e.:
createSession:
- Create session
- Create req.login["Logged_in"]

getSameSession:
- Check if  req.login["Logged_in"] is set.
- If  req.login["Logged_in"] isn't set (we aren't doing an "internal" 
call), then try to load the variables from our session.

But how secure is this? And is there another way to handle this?
I could also store the whole session object in the req  - - but ..  it 
isn't very smart.

And why does it happen (quite often!) that the session handling make 
Apache server spin in an infinitive loop!?

Kind regards
Amir Salihefendic
-----
What we do in life echoes in eternity



More information about the Mod_python mailing list