Using SESSION with Google App Engine and Python 2.7

So recently I was lucky enough to be part of a Google training session at Canterbury University, where Google Engineer James McGill gave a hands-on workshop on using Google App Engine with Python (2.7)  It opened a whole new avenue of web development to me, and I was able to use it to succesfully complete an assignment just a few weeks later.

Something I needed was a session variable (or maybe I didn't, and I just thought I did - either way, I needed one Cool ), and while this isn't built in there are a few different session libraries for GAE with Python and I tried the one that was most widely recommended in Google searches - gaeutilities, but this caused errors and wouldn't work (I eventually stumbled across this post on Stack Overflow to explain that its just not compatible with Python 2.7). A little more searching led me to this library from appenginelearn.com which I dropped in and it worked perfectly... until I deployed it - then it just does nothing - which was a little frustrating.

Eventually I was shown that the framework I was using (WebApp2) actually has its own session library in a package called webapp2_extras which makes the whole thing much simpler and it works out of the box.

The process to use it is as follows:

Import the library

from webapp2_extras import sessions

 

Create a base handler

class BaseHandler(webapp2.RequestHandler):
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)
 
        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)
 
    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

 

Create the index.html page handler, with the user variable being extracted from session and send to the page template

class MainPage(BaseHandler):
    def get(self):
        user = self.session.get('user')
        template_values = {
            'user': user
            }
        template = jinja_environment.get_template('main.html')
        self.response.out.write(template.render(template_values))

 

Then create the login page handler

class LogIn(BaseHandler):
    def get(self):
        if self.session.get('user'):
            del self.session['user']
        if not self.session.get('referrer'):
            self.session['referrer'] = \
                self.request.environ['HTTP_REFERER'] \
                if 'HTTP_REFERER' in self.request.environ \
                else '/'
        template_values = {
            }
        template = jinja_environment.get_template('login.html')
        self.response.out.write(template.render(template_values))
 
    def post(self):
        user = self.request.get('user')
        self.session['user'] = user
        logging.info("%s just logged in" % user)
        self.redirect('/')

 

And simply put the following code in your HTML template somewhere to show the user who is logged in

{% if user %}
    <div id="user">
        Welcome, {{user}}
    </div>
{% endif %}