Skip to content
Myr

Added EXPLAIN_TEMPLATE_LOADING to help people debug templates not being loaded.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent f17ad95 · Browse files · 11 files+170 added−15 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+170 added−15 removed

  • other:+170 added−15 removed

11 files+170 added−15 removed

modified:docs/blueprints.rst+18 added
183 unmodified lines
184want to render the template ``'admin/index.html'`` and you have provided185``templates`` as a `template_folder` you will have to create a file like186this: ``yourapplication/admin/templates/admin/index.html``.187188To further reiterate this: if you have a blueprint named ``admin`` and you189want to render a template called ``index.html`` which is specific to this190blueprint, the best idea is to lay out your templates like this::191192 yourpackage/193 blueprints/194 admin/195 templates/196 admin/197 index.html198 __init__.py199200And then when you want to render the template, use ``admin/index.html`` as201the name to look up the template by. If you encounter problems loading202the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config203variable which will instruct Flask to print out the steps it goes through204to locate templates on every ``render_template`` call.205206Building URLs207-------------208209If you want to link from one page to another you can use the
28 unmodified lines
modified:docs/config.rst+9 added-4 removed
186 unmodified lines
187 necessary. But disk I/O is costly and it may188 be viable to disable this feature by setting189 this key to ``False``. This option does not190 affect debug mode.191``EXPLAIN_TEMPLATE_LOADING`` If this is enabled then every attempt to192 load a template will write an info193 message to the logger explaining the194 attempts to locate the template. This195 can be useful to figure out why196 templates cannot be found or wrong197 templates appear to be loaded.198================================= =========================================199200.. admonition:: More on ``SERVER_NAME``201
38 unmodified lines
240.. versionadded:: 0.10241 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``242243.. versionadded:: 1.0237 ``SESSION_REFRESH_EACH_REQUEST``244 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,245 ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``246239.. versionadded:: 1.0240 ``TEMPLATES_AUTO_RELOAD``, ``LOGGER_HANDLER_POLICY``241247Configuring from Files248----------------------249250Configuration becomes more useful if you can store it in a separate file,
213 unmodified lines
modified:flask/testsuite/test_apps/blueprintapp/apps/frontend/__init__.py+5 added
4 unmodified lines
56@frontend.route('/')7def index():8 return render_template('frontend/index.html')91011@frontend.route('/missing')12def missing_template():13 return render_template('missing_template.html')
modified:flask/testsuite/test_apps/blueprintapp/__init__.py+1 added
1from flask import Flask23app = Flask(__name__)4app.config['DEBUG'] = True5from blueprintapp.apps.admin import admin6from blueprintapp.apps.frontend import frontend7app.register_blueprint(admin)8app.register_blueprint(frontend)
modified:flask/testsuite/templating.py+42 added
9 unmodified lines
10"""1112import flask13import unittest14import logging15from jinja2 import TemplateNotFound1617from flask.testsuite import FlaskTestCase181920class TemplatingTestCase(FlaskTestCase):
284 unmodified lines
305 app = flask.Flask(__name__)306 app.config['TEMPLATES_AUTO_RELOAD'] = False307 self.assert_false(app.jinja_env.auto_reload)308309 def test_template_loader_debugging(self):310 from blueprintapp import app311312 called = []313 class _TestHandler(logging.Handler):314 def handle(x, record):315 called.append(True)316 text = unicode(record.msg)317 self.assert_('1: trying loader of application '318 '"blueprintapp"' in text)319 self.assert_('2: trying loader of blueprint "admin" '320 '(blueprintapp.apps.admin)' in text)321 self.assert_('trying loader of blueprint "frontend" '322 '(blueprintapp.apps.frontend)' in text)323 self.assert_('Error: the template could not be found' in text)324 self.assert_('looked up from an endpoint that belongs to '325 'the blueprint "frontend"' in text)326 self.assert_(327 'See http://flask.pocoo.org/docs/blueprints/#templates' in text)328329 with app.test_client() as c:330 try:331 old_load_setting = app.config['EXPLAIN_TEMPLATE_LOADING']332 old_handlers = app.logger.handlers[:]333 app.logger.handlers = [_TestHandler()]334 app.config['EXPLAIN_TEMPLATE_LOADING'] = True335336 try:337 c.get('/missing')338 except TemplateNotFound as e:339 self.assert_('missing_template.html' in str(e))340 else:341 self.fail('Expected template not found exception.')342 finally:343 app.logger.handlers[:] = old_handlers344 app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting345346 self.assert_equal(len(called), 1)347348349def suite():350 suite = unittest.TestSuite()351 suite.addTest(unittest.makeSuite(TemplatingTestCase))352 return suite
modified:flask/app.py+1 added
290 unmodified lines
291 'MAX_CONTENT_LENGTH': None,292 'SEND_FILE_MAX_AGE_DEFAULT': 12 * 60 * 60, # 12 hours293 'TRAP_BAD_REQUEST_ERRORS': False,294 'TRAP_HTTP_EXCEPTIONS': False,295 'EXPLAIN_TEMPLATE_LOADING': False,296 'PREFERRED_URL_SCHEME': 'http',297 'JSON_AS_ASCII': True,298 'JSON_SORT_KEYS': True,299 'JSONIFY_PRETTYPRINT_REGULAR': True,
1581 unmodified lines
modified:flask/debughelpers.py+69 added-1 removed
6 unmodified lines
78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from ._compat import implements_to_string11from ._compat import implements_to_string, text_type12from .app import Flask13from .blueprints import Blueprint14from .globals import _request_ctx_stack151617class UnexpectedUnicodeError(AssertionError, UnicodeError):18 """Raised in places where we want some better error reporting for
68 unmodified lines
87 raise DebugFilesKeyError(request, key)88 newcls.__name__ = oldcls.__name__89 newcls.__module__ = oldcls.__module__90 request.files.__class__ = newcls919293def _dump_loader_info(loader):94 yield 'class: %s.%s' % (type(loader).__module__, type(loader).__name__)95 for key, value in sorted(loader.__dict__.items()):96 if key.startswith('_'):97 continue98 if isinstance(value, (tuple, list)):99 if not all(isinstance(x, (str, text_type)) for x in value):100 continue101 yield '%s:' % key102 for item in value:103 yield ' - %s' % item104 continue105 elif not isinstance(value, (str, text_type, int, float, bool)):106 continue107 yield '%s: %r' % (key, value)108109110def explain_template_loading_attempts(app, template, attempts):111 """This should help developers understand what """112 info = ['Locating template "%s":' % template]113 total_found = 0114 blueprint = None115 reqctx = _request_ctx_stack.top116 if reqctx is not None and reqctx.request.blueprint is not None:117 blueprint = reqctx.request.blueprint118119 for idx, (loader, srcobj, triple) in enumerate(attempts):120 if isinstance(srcobj, Flask):121 src_info = 'application "%s"' % srcobj.import_name122 elif isinstance(srcobj, Blueprint):123 src_info = 'blueprint "%s" (%s)' % (srcobj.name,124 srcobj.import_name)125 else:126 src_info = repr(srcobj)127128 info.append('% 5d: trying loader of %s' % (129 idx + 1, src_info))130131 for line in _dump_loader_info(loader):132 info.append(' %s' % line)133134 if triple is None:135 detail = 'no match'136 else:137 detail = 'found (%r)' % (triple[1] or '<string>')138 total_found += 1139 info.append(' -> %s' % detail)140141 seems_fishy = False142 if total_found == 0:143 info.append('Error: the template could not be found.')144 seems_fishy = True145 elif total_found > 1:146 info.append('Warning: multiple loaders returned a match for the template.')147 seems_fishy = True148149 if blueprint is not None and seems_fishy:150 info.append(' The template was looked up from an endpoint that '151 'belongs to the blueprint "%s".' % blueprint)152 info.append(' Maybe you did not place a template in the right folder?')153 info.append(' See http://flask.pocoo.org/docs/blueprints/#templates')154155 app.logger.info('\n'.join(info))
modified:flask/sessions.py+1 added-3 removed
69 unmodified lines
70 elif isinstance(value, str):71 try:72 return text_type(value)73 except UnicodeError:74 from flask.debughelpers import UnexpectedUnicodeError75 raise UnexpectedUnicodeError(u'A byte string with '76 u'non-ASCII data was passed to the session system '77 u'which can only store unicode strings. Consider '78 u'base64 encoding your string (String was %r)' % value)
283 unmodified lines
362 val = self.get_signing_serializer(app).dumps(dict(session))363 response.set_cookie(app.session_cookie_name, val,364 expires=expires, httponly=httponly,365 domain=domain, path=path, secure=secure)365366367from flask.debughelpers import UnexpectedUnicodeError
modified:flask/templating.py+20 added-6 removed
6 unmodified lines
78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import posixpath11from jinja2 import BaseLoader, Environment as BaseEnvironment, \12 TemplateNotFound1314from .globals import _request_ctx_stack, _app_ctx_stack
37 unmodified lines
52 def __init__(self, app):53 self.app = app5455 def get_source(self, environment, template):56 explain = self.app.config['EXPLAIN_TEMPLATE_LOADING']57 attempts = []58 tmplrv = None5957 for loader, local_name in self._iter_loaders(template):60 for srcobj, loader in self._iter_loaders(template):61 try:59 return loader.get_source(environment, local_name)62 rv = loader.get_source(environment, template)63 if tmplrv is None:64 tmplrv = rv65 if not explain:66 break67 except TemplateNotFound:61 pass68 rv = None69 attempts.append((loader, srcobj, rv))7071 if explain:72 from debughelpers import explain_template_loading_attempts73 explain_template_loading_attempts(self.app, template, attempts)7475 if tmplrv is not None:76 return tmplrv77 raise TemplateNotFound(template)7879 def _iter_loaders(self, template):80 loader = self.app.jinja_loader81 if loader is not None:68 yield loader, template82 yield self.app, loader8384 for blueprint in itervalues(self.app.blueprints):85 loader = blueprint.jinja_loader86 if loader is not None:73 yield loader, template87 yield blueprint, loader8889 def list_templates(self):90 result = set()91 loader = self.app.jinja_loader
48 unmodified lines
modified:flask/wrappers.py+1 added-1 removed
10 unmodified lines
1112from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13from werkzeug.exceptions import BadRequest1415from .debughelpers import attach_enctype_error_multidict15from . import json16from .globals import _request_ctx_stack1718
163 unmodified lines
182 # subclass that raises a different error for key errors.183 ctx = _request_ctx_stack.top184 if ctx is not None and ctx.app.debug and \185 self.mimetype != 'multipart/form-data' and not self.files:186 from .debughelpers import attach_enctype_error_multidict187 attach_enctype_error_multidict(self)188189190class Response(ResponseBase):
9 unmodified lines
modified:CHANGES+3 added
39 unmodified lines
40- Flask will now log by default even if debug is disabled. The log format is41 now hardcoded but the default log handling can be disabled through the42 ``LOGGER_HANDLER_POLICY`` configuration key.43- Removed deprecate module functionality.44- Added the ``EXPLAIN_TEMPLATE_LOADING`` config flag which when enabled will45 instruct Flask to explain how it locates templates. This should help46 users debug when the wrong templates are loaded.4748Version 0.10.249--------------50
478 unmodified lines