TurboGears – Cookies & Sessions



It is often required to hold simple browsing data attached to a user’s browser. Sessions are the most commonly used technique. Session represents data which need not be stored in a more persistent form like disk file or database.

However, sessiondata in TurboGears can be backed by filesystem, database or hashed cookie values. A small amount of session data is generally kept in cookies, but for the larger volume of session data MemCache is used.

MemCache is a system-level daemon. It provides fast access to cached data and is extremely scalable. However, it is intended for use only on secure servers, and hence must be maintained and secured by sysadmin.

Beaker in Session Management

TurboGears uses Beaker for session management. A project quickstarted by gearbox is by default configured to use hashed cookies to store session data.

Each time a client connects, the session middleware (Beaker) will inspect the cookie using the cookie name, which has been defined in the configuration file. If the cookie is not found, it will be set in the browser. On all subsequent visits, the middleware will find the cookie and make use of it.

In order to enable session management, session class should be incorporated in the project by following import statement −

from tg import session

To save the data in a session variable −

session[‘key’] = value
session.save()

To retrieve the session variable −

return session[‘key’]

Note that you need to explicitly save the session in order for your keys to be stored in that session.

The delete() method of the session object will erase all the user sessions −

session.delete()

Even though it’s not customary to delete all the user sessions on any given production environment, you will typically do it for cleaning up after usability or functional tests have been done.

Given below is a simple example to demonstrate sessions. RootController class has a setsession() method which sets a session variable.

from hello.lib.base import BaseController
from tg import expose, session
class RootController(BaseController):
   
   @expose()
   def setsession(self):
      session['user'] = 'MVL'
      session.save()
      
      str = "<b>sessionVariable set to "+session['user'] 
      str = str+"<br><a href = '/getsession'>click here to retrieve</a></b>"
      return str
   
   @expose()
   def getsession(self):
      return "<b>value of session variable retrieved " +session['user'] +"</b>"

Enter http://localhost:8080/setsession

Session

A link in the browser leads to http://localhost:8080/getsession which retrieves and displays the session variable −

Variable
Advertisements