GAE 프로젝트에서 Webapp2와 함께 Jinja2를 사용합니다.
에 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 환경이나 템플릿 로더 구성처럼?
문제 원인 : Jinja2 기본 로더는 상대 ./templates/
디렉토리 에서 파일을 검색합니다 . 개발 서버에서 GAE 애플리케이션을 실행할 때이 경로는 애플리케이션의 루트에 상대적입니다. 그러나 unittest를 실행할 때이 경로는 unittest 파일에 상대적입니다.
솔루션 : 이상적인 솔루션은 아니지만 여기에 내 문제를 해결하기 위해 한 트릭이 있습니다.
앱 구성에 설정된 동적 템플릿 경로를 추가하도록 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
그리고 내 unittests의 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})
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다