Tuesday, October 4, 2011

Session handling in Python

My project has registered users and I need to keep login accounts for them. It is very important that I need to handle the sessions of each user, efficiently. Session handling in python is not a big deal, but for a beginner it will be difficult to find correct documentation for it. So I think it will be useful to those people who are working with the same tools. We need to set the following lines of code outside all classes,

store = web.session.DiskStore('sessions')
if web.config.get('_session') is None:
        session = web.session.Session(app,store,initializer={'login': 0, 'privilege': 0, 'user':'anonymous', 'loggedin':False})
        web.config._session = session
        session = web.config._session

We need to first set the user as anonymous and loggedin as false. Then we need to change these values upon the sign in operation. When a user sign in to the wiki using his mail id and password, we need to add the following lines with that operation,

session.loggedin = True
session.email = fi.email
session.user = fi.fname

You can decide whether the session.user has to store mail id or first name. It is important that session.user holds the login id. In my project session.email holds the unique login id.

Now we can think about sign out operation. On sign out, we need to destroy the session of that particular user. Her we got the code,


This line will kill the current session and now the user needs to log in again. That’s all about the basic session handling. If you want to know more about the session you can refer webpy site.



No comments:

Post a Comment

Comments with advertisement links will not be published. Thank you.