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:<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 GAE, GAE-Session, Google App Engine, Python, Session. Bookmark the permalink. Both comments and trackbacks are currently closed.
Nessun commento:
Posta un commento