Sessions

HTTP Requests are Stateless

Web requests are stateless. 'stateless' means 'memory-less'. The 'state' of the world is lost on each request.

The server doesn't remember variables on each browser request. Your server code may have data members, but they're re-initialized on each request.

Session Variables

Session variables are the way to get around the statelessness of web requests.

Session variables remember data from request to request, and specifically for each user.

Even if your site doesn't require login, you can use session variables to track information about each visitor.

Session variables use cookies to record information. Cookies are little bits of information stored on the client's computer.

Session variables are generally key-value pairs.

As an example, consider the game Mastermind. What variables would you want to store in the 'session' object.

Session Management and Google's App Engine.


Web frameworks, such as Google App Engine's, provide methods for storing and retrieving session information. For App Engine, session information is not built in but there have been some tools released for it: GAE tools. Django and other frameworks provide their own help for session management.

For this lesson, will use the GAE tool version. You can download the newest from
GAE tools, or the attachment below.

Download the file into the directory of your AppEngine application. Then in your controller code, import 'sessions' at the top of your file.

At that point, you can access a hash table for the session in any controller function. Here's how:

    sess = sessions.Session()

Once you have the variable 'sess', you can set or retrieve key-value pairs in Python's dictionary style, e.g.

    sess['secret']=secret  # set
    x = sess['guessList']

Here's some sample code for a Mastermind game:   


import sessions
import mastermind

class MainPage(webapp.RequestHandler):
  def get(self):
    # create a Session object using the imported module.
    sess = sessions.Session()
    # generate the secret code and store it in the session hash table
    sess['secret']=mastermind.generateSecret()
    # ...

Instructor Demo: Write an application that counts the number of times a visitor to the site clicks a button.

Attachments (1)

Recent site activity