Search code examples
pythongoogle-app-enginesessionjinja2webapp2

Access session variable in jinja2 or set global variable in jinja2 webapp2 python


I am working on a webapp2 python project. Is there any way with which i can access the session variable in jinja2 templates. I know that we can get the session variable and then pass it to the template then we can use it. But i have alot of handlers and i do not want to pass the session variables each time to the render function. I am looking for something like we can do in php access direct session values in template. Any help would be appreciated.


Solution

  • Or use the BaseHandler to add template context:

    class BaseHandler(webapp2.RequestHandler):
        """ webapp2 base handler """
    
        def __init__(self, request, response):
    
            self.session_store = None
            super(BaseHandler, self).__init__(request, response)
            user = users.get_current_user()
            # if not users.is_current_user_admin():
            if user.email() not in USER_CONFIG:
                self.abort(401)
    
        def dispatch(self):
    
            # Get a session store for this request.
            self.session_store = sessions.get_store(request=self.request)
            if not self.session:
                session_data_or_default(self.session)
            try:
                # Dispatch the request.
                webapp2.RequestHandler.dispatch(self)
            finally:
                self.session['route_name'] = self.request.route.name
                # Save all sessions.
                self.session_store.save_sessions(self.response)
    
        @webapp2.cached_property
        def session(self):
            # Returns a session using the default cookie key.
            # we use memcache because the amount of data you can store in a secure cookie is limited.
            return self.session_store.get_session(name='my-secret-session', backend='memcache')
    
        @webapp2.cached_property
        def jinja2(self):
            return jinja2.get_jinja2(app=self.app)
    
        def render_template(self, template, **template_args):
            template_args['session'] = self.session
            template_args['version'] = modules.get_current_version_name()
    
            self.response.write(self.jinja2.render_template(template, **template_args))
    
        def return_rendered(self, template, **template_args):
            template_args['session'] = self.session
    
            return self.jinja2.render_template(template, **template_args)