domenica 7 aprile 2013

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

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
- url: /.*

5. Create your file

Within your app directory create an 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 file

Within your app directory create a 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)],
def main():
if __name__ == "__main__":

8. Create your index.html file

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

<html lang="en">
<title>GAE Sessions</title>
Counter = {{ counter}}

9. Run your application

My GAE installation is located in /opt/google_appengine/ so I start the application with the command:
/opt/google_appengine/ 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.

1 commento:

  1. You need to kill time, you need entertainment. Refer to our website. hope you get the most comfort.
    Thanks you for sharing!
    Friv 4