Skip to content

Instantly share code, notes, and snippets.

@syakesaba
Created August 12, 2014 14:57
Show Gist options
  • Select an option

  • Save syakesaba/d5b5b7e27d7fbe923c25 to your computer and use it in GitHub Desktop.

Select an option

Save syakesaba/d5b5b7e27d7fbe923c25 to your computer and use it in GitHub Desktop.
jinja2にJSP以上の機能を持たせるRequestHandler、template_nameに基づくHTMLキャッシュ機能
class BaseRequestHandler(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)
except Exception as e:
logging.info(e)
self.redirect(self.uri_for("main"))
finally:
# Save all sessions.
self.session_store.save_sessions(self.response)
@webapp2.cached_property
def jinja2(self):
"""
@return: jinja2 environment instance
@rtype: jinja2.Environment
"""
return jinja2.get_jinja2(app=self.app)
@webapp2.cached_property
def session(self):
"""
@return: session dictionary(auto-save)
@rtype: webapp2_extras.sessions.Session
"""
return self.session_store.get_session()
def render(self, template_name, template_vars={}):
# Preset values for the template
values = {
'uri_for': self.uri_for,
'flashes': self.session.get_flashes(),
'template_name': template_name,
'handler':self,
'request':self.request,
'response':self.response,
'session':self.session
}
# Add manually supplied template values
values.update(template_vars)
# read the template or 404.html
try:
self.response.write(self.jinja2.render_template(template_name, **values))
except TemplateNotFound as e:
logging.info(e + " %s not found" % template_name)
self.abort(404)
def render_str(self, template_name, template_vars={}):
# Preset values for the template
values = {
'uri_for': self.uri_for,
'flashes': self.session.get_flashes(),
'template_name': template_name,
'handler':self,
'request':self.request,
'response':self.response,
'session':self.session
}
# Add manually supplied template values
values.update(template_vars)
# read the template or 404.html
try:
return self.jinja2.render_template(template_name, **values)#.encode("UTF-8"))
except TemplateNotFound as e:
logging.info(e + " %s not found" % template_name)
return None
def render_cached(self, template_name, template_vars={}):
cached_template = memcache.get(template_name) # @UndefinedVariable
if cached_template is None:
cached_template = self.render_str(template_name, template_vars)
memcache.add(template_name, cached_template) # @UndefinedVariable
self.response.write(cached_template)
def render_str_cached(self, template_name, template_vars={}):
cached_template = memcache.get(template_name) # @UndefinedVariable
if cached_template is None:
cached_template = self.render_str(template_name, template_vars)
memcache.add(template_name, cached_template) # @UndefinedVariable
return cached_template
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment