How to use sessions on Google App Engine with Python and gae-sessions?

Google App Engine with Python does not provide built in session capabilities. This step by step walkthrough sets up a Google App Engine app using the lightweight gae-sessions utility.

1. Download gae-sessions

Download the gae-sessions code from https://github.com/dound/gae-sessions/

2. Create your app directory

Create a directory for your application. I’ll be using gaesessiontest/

3. Copy gaesessions to your app

From the gae-sessions download file, copy the gaesessions/ directory to your app directory.

4. Create your app.yaml file

Within your app directory create an app.yaml file with the contents:

application: gaesessiontest
version: 1
runtime: python
api_version: 1
 
handlers:
- url: /.*
  script: main.py

5. Create your appengine_config.py file

Within your app directory create an appengine_config.py file with the contents:

from gaesessions import SessionMiddleware
def webapp_add_wsgi_middleware(app):
    app = SessionMiddleware(app, cookie_key="You must change this")
    return app

6. Change the cookie_key

Change the cookie_key value to a secret combination of characters.

7. Create your main.py file

Within your app directory create a main.py file with the contents:

import os
 
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
 
from gaesessions import get_current_session
 
class MainPage(webapp.RequestHandler):
    def get(self):
 
        # Get the current session        
        session = get_current_session()
 
        # Get the value of the counter,
        # defaulting to 0 if not present
        counter = session.get('counter', 0)
 
        # Increment the counter
        session['counter'] =  counter + 1 
 
        context = {
             "counter": counter 
        }
 
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, context))
 
application = webapp.WSGIApplication(
                                     [('/', MainPage)],
                                     debug=True)
 
def main():
    run_wsgi_app(application)
 
if __name__ == "__main__":
    main()

8. Create your index.html file

Within your app directory create an index.html file with the contents:

<!DOCTYPE html>
<html lang="en">
<head>
<title>GAE Sessions</title>
</head>
<body>
Counter = {{ counter}}
</body>
</html>

9. Run your application

My GAE installation is located in /opt/google_appengine/ so I start the application with the command:

/opt/google_appengine/dev_appserver.py gaesessiontest

10. View your app

Open your browser and go to http://localhost:8080/. You should see a counter that increments each time you refresh the page.

This entry was posted in Google App Engine and tagged , , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

4 Comments

  1. Posted May 25, 2011 at 2:27 pm | Permalink

    On the line where you increment the counter:
    session['counter'] = session['counter'] + 1
    the 2nd “session['counter']” should be replaced by “counter” like this:
    session['counter'] = counter + 1
    because you’re retrieving a value that does not exist yet (on the first visit) and this will generate a KeyError.

    Thanks for the post btw. Nice to-the-point example.

  2. Anonymous
    Posted September 4, 2011 at 5:21 pm | Permalink

    Works like a charm!

  3. Posted September 4, 2011 at 10:43 pm | Permalink

    @Jeroen, thanks for the fix – post updated.

  4. Nishant
    Posted October 17, 2012 at 9:03 am | Permalink

    I am new to google app engine , i am using gaesession to my application in gaesession __init__.py showing some errors like

    pdump = memcache.get(self.sid, namespace=”)

    get is undefined.

One Trackback

  1. [...] This post was mentioned on Twitter by cfbloggers. cfbloggers said: How to use sessions on Google App Engine with Python and gae-sessions? – http://cfbloggers.org/?c=46806 [...]