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:
# Get a session store for this request.
self.session_store = sessions.get_store(request=self.request)
# Dispatch the request.
# Save all sessions.
# Returns a session using the default cookie key.
sess = self.session_store.get_session()
#add some default values:
if not sess.get(‘theme’):
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:
template = JINJA_ENVIRONMENT.get_template(‘stereo.html’)