哪个是在App Engine上使用jinja2的首选方法?

Jed*_*sen 10 python google-app-engine jinja2

我最初使用App Engine网站上显示的示例在App Engine上实现了Jinja2:https://developers.google.com/appengine/docs/python/gettingstartedpython27/templates jinja2直接导入的位置:

import jinja2
import os

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class MainPage(webapp2.RequestHandler):
    def get(self):
        greetings = 'somestring'
        template_values = {
            'greetings': greetings,
        }
        template = jinja_environment.get_template('index.html')
        self.response.out.write(template.render(template_values))
Run Code Online (Sandbox Code Playgroud)

但我现在正在使用Simpleauth(https://github.com/crhym3/simpleauth),它遵循Nick Johnson在此描述的实现:http://blog.notdot.net/2011/11/Migrating-to-Python -2-7-part-2-Webapp-and-templates,其中jinja2是从webapp2_extras导入的:

import os
import webapp2
from webapp2_extras import jinja2

class BaseHandler(webapp2.RequestHandler):
  @webapp2.cached_property
  def jinja2(self):
        return jinja2.get_jinja2(app=self.app)

  def render_template(self, filename, **template_args):
        self.response.write(self.jinja2.render_template(filename, **template_args))

class IndexHandler(BaseHandler):
  def get(self):
    self.render_template('index.html', name=self.request.get('name'))
Run Code Online (Sandbox Code Playgroud)

以下哪一项是使用jinja2的首选方法?(他们似乎没有很好地合作,并且更愿意标准化最好的选择.)

ale*_*lex 3

我想他们几乎是一样的。webapp2_extras.jinja2 另外做的是缓存 jinja2.Environment() 初始化(在请求持续时间内)。另外,您可以利用 webapp2 的配置/注册表系统。

查看get_jinja2() 源代码,您会发现它只是 jinja2.Environment() 的一个方便的包装器,带有一些默认环境参数和启用的扩展(例如 i18n)。