2

我在 GAE 项目中使用 Jinja2 和 Webapp2。

我有一个RequestHandler如下所述的基础webapp2_extras.jinja2

import webapp2

from webapp2_extras import jinja2


def jinja2_factory(app):
    """Set configuration environment for Jinja."""
    config = {my config...}
    j = jinja2.Jinja2(app, config=config)
    return j


class BaseHandler(webapp2.RequestHandler):

    @webapp2.cached_property
    def jinja2(self):
        # Returns a Jinja2 renderer cached in the app registry.
        return jinja2.get_jinja2(factory=jinja2_factory, app=self.app)

    def render_response(self, _template, **context):
        # Renders a template and writes the result to the response.
        rv = self.jinja2.render_template(_template, **context)
        self.response.write(rv)

和一个视图处理程序:

class MyHandler(BaseHandler):
    def get(self):
        context = {'message': 'Hello, world!'}
        self.render_response('my_template.html', **context)

我的模板位于默认位置 ( templates)。

该应用程序在开发服务器上运行良好,并且模板已正确呈现。

但是当我尝试MyHandler

import unittest
import webapp2
import webstest

class MyHandlerTest(unittest.TestCase):

    def setUp(self):
        application = webapp2.WSGIApplication([('/', MyHandler)])
        self.testapp = webtest.TestApp(application)

    def test_response(self):
        response = application.get_response('/')
        ...

application.get_response('/my-view')引发异常:TemplateNotFound: my_template.html.

有什么我错过的吗?像 jinja2 环境或模板加载器配置?

4

1 回答 1

3

问题根源: Jinja2 默认加载器在相对./templates/目录中搜索文件。当您在开发服务器上运行 GAE 应用程序时,此路径相对于应用程序的根目录。但是当你运行你的单元测试时,这个路径是相对于你的单元测试文件的。

解决方案: 这不是一个理想的解决方案,但这是我解决问题的一个技巧。

我更新了 jinja2 工厂以添加动态模板路径,在应用程序配置中设置:

def jinja2_factory(app):
    """Set configuration environment for Jinja."""
    config = {'template_path': app.config.get('templates_path', 'templates'),}
    j = jinja2.Jinja2(app, config=config)
    return j

我在单元测试的 setUp 中设置了模板的绝对路径:

class MyHandlerTest(unittest.TestCase):

    def setUp(self):
        # Set template path for loader
        start = os.path.dirname(__file__)
        rel_path = os.path.join(start, '../../templates') # Path to my template
        abs_path = os.path.realpath(rel_path)
        application.config.update({'templates_path': abs_path})
于 2013-10-17T10:14:15.020 回答