How to handle sessions in Google app engine

While developing a GAE app engine recently, I came across the need to handle session variables. While session was a thing that I use to take for granted in ASP.NET (Session["xyz"]) or php ($_SESSION['xyz']), storing and fetching session variables isn’t something that straightforward with webapp2, the web framework widely used for building GAE apps with python.

However, I found a pretty easy way to implement sessions in my existing app (which was almost half-way done!) by creating a simple BaseHandler class that is session-powered, and then deriving all my url handlers with this new class instead of the usual webapp2.RequestHandler. Once you do that, you can straightaway use the python dictionary self.session['my_variable'] (that pretty much resembles $_SESSION['my_var'] in php). Here is the implementation for BaseHandler:

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.
        sess = self.session_store.get_session()
        #add some default values:
        if not sess.get(‘theme’):
            sess['theme']=’cosmo’#’slate’
        return sess

Here, you may initialize any particular session variables if you want and set default values for them (as I’ve done for the cosmo theme above).

Hopefully, this should save you some development time if you want to implement sessions in existing app engine code. As an example, here is how I make use of a session variable to pass on a user’s preferred theme to the template engine, so that the webpage can be displayed accordingly:

class MainPage(BaseHandler):
    def get(self):
        template = JINJA_ENVIRONMENT.get_template(‘stereo.html’)
        if self.request.get(‘theme’):
            theme=self.request.get(‘theme’)
            self.session['theme']=theme
        else:
            theme=self.session['theme']
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s