Webapp2 Sessions In Google App Engine
I just figured out how to implement the webapp2 sessions in my Google app engine project using python. The code is below. What I would like to know is what is the best approach to
Solution 1:
The way I handled sessions was to create a BaseHandler class deriving from webapp2.RequestHandler. I equipped BaseHandler class with all session initialization and default session values and reused this class to create each handler instead of directly deriving from webapp2.RequestHandler.
The obvious advantage of this is that you don't have to repeat session initialization each time you have to use a session in a file.
classBaseHandler(webapp2.RequestHandler):
defdispatch(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_propertydefsession(self):
# Returns a session using the default cookie key.
sess = self.session_store.get_session()
#add some default values:ifnot sess.get('theme'):
sess['theme']='cosmo'#'slate'return sess
classMainPage(BaseHandler):
defget(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']
Refer my article for more details.
Post a Comment for "Webapp2 Sessions In Google App Engine"