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
Provenance
- Commit
bafc139- Tree
b35fd07- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f17ad95
11 files changed+170 added−15 removed
modified:docs/blueprints.rst+18 added
183 unmodified lines184 want to render the template ``'admin/index.html'`` and you have provided185 ``templates`` as a `template_folder` you will have to create a file like186 this: ``yourapplication/admin/templates/admin/index.html``.187 188+To further reiterate this: if you have a blueprint named ``admin`` and you189+want to render a template called ``index.html`` which is specific to this190+blueprint, the best idea is to lay out your templates like this::191+192+ yourpackage/193+ blueprints/194+ admin/195+ templates/196+ admin/197+ index.html198+ __init__.py199+200+And then when you want to render the template, use ``admin/index.html`` as201+the name to look up the template by. If you encounter problems loading202+the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config203+variable which will instruct Flask to print out the steps it goes through204+to locate templates on every ``render_template`` call.205+206 Building URLs207 -------------208 209 If you want to link from one page to another you can use the28 unmodified linesmodified:docs/config.rst+9 added-4 removed
186 unmodified lines187 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 ================================= =========================================199 200 .. admonition:: More on ``SERVER_NAME``201 38 unmodified lines240 .. versionadded:: 0.10241 ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``242 243 .. versionadded:: 1.0237- ``SESSION_REFRESH_EACH_REQUEST``244+ ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,245+ ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``246 239-.. versionadded:: 1.0240- ``TEMPLATES_AUTO_RELOAD``, ``LOGGER_HANDLER_POLICY``241-247 Configuring from Files248 ----------------------249 250 Configuration becomes more useful if you can store it in a separate file,213 unmodified linesmodified:flask/testsuite/test_apps/blueprintapp/apps/frontend/__init__.py+5 added
4 unmodified lines5 6 @frontend.route('/')7 def index():8 return render_template('frontend/index.html')9+10+11+@frontend.route('/missing')12+def missing_template():13+ return render_template('missing_template.html')modified:flask/testsuite/test_apps/blueprintapp/__init__.py+1 added
1 from flask import Flask2 3 app = Flask(__name__)4+app.config['DEBUG'] = True5 from blueprintapp.apps.admin import admin6 from blueprintapp.apps.frontend import frontend7 app.register_blueprint(admin)8 app.register_blueprint(frontend)modified:flask/testsuite/templating.py+42 added
9 unmodified lines10 """11 12 import flask13 import unittest14+import logging15+from jinja2 import TemplateNotFound16+17 from flask.testsuite import FlaskTestCase18 19 20 class TemplatingTestCase(FlaskTestCase):284 unmodified lines305 app = flask.Flask(__name__)306 app.config['TEMPLATES_AUTO_RELOAD'] = False307 self.assert_false(app.jinja_env.auto_reload)308 309+ def test_template_loader_debugging(self):310+ from blueprintapp import app311 312+ 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)328+329+ 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'] = True335+336+ 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_setting345+346+ self.assert_equal(len(called), 1)347+348+349 def suite():350 suite = unittest.TestSuite()351 suite.addTest(unittest.makeSuite(TemplatingTestCase))352 return suitemodified:flask/app.py+1 added
290 unmodified lines291 '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 linesmodified:flask/debughelpers.py+69 added-1 removed
6 unmodified lines7 8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-from ._compat import implements_to_string11+from ._compat import implements_to_string, text_type12+from .app import Flask13+from .blueprints import Blueprint14+from .globals import _request_ctx_stack15 16 17 class UnexpectedUnicodeError(AssertionError, UnicodeError):18 """Raised in places where we want some better error reporting for68 unmodified lines87 raise DebugFilesKeyError(request, key)88 newcls.__name__ = oldcls.__name__89 newcls.__module__ = oldcls.__module__90 request.files.__class__ = newcls91+92+93+def _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)108+109+110+def 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.blueprint118+119+ 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)127+128+ info.append('% 5d: trying loader of %s' % (129+ idx + 1, src_info))130+131+ for line in _dump_loader_info(loader):132+ info.append(' %s' % line)133+134+ 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)140+141+ 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 = True148+149+ 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')154+155+ app.logger.info('\n'.join(info))modified:flask/sessions.py+1 added-3 removed
69 unmodified lines70 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 lines362 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)365-366-367-from flask.debughelpers import UnexpectedUnicodeErrormodified:flask/templating.py+20 added-6 removed
6 unmodified lines7 8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-import posixpath11 from jinja2 import BaseLoader, Environment as BaseEnvironment, \12 TemplateNotFound13 14 from .globals import _request_ctx_stack, _app_ctx_stack37 unmodified lines52 def __init__(self, app):53 self.app = app54 55 def get_source(self, environment, template):56+ explain = self.app.config['EXPLAIN_TEMPLATE_LOADING']57+ attempts = []58+ tmplrv = None59+57- 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))70 71+ if explain:72+ from debughelpers import explain_template_loading_attempts73+ explain_template_loading_attempts(self.app, template, attempts)74+75+ if tmplrv is not None:76+ return tmplrv77 raise TemplateNotFound(template)78 79 def _iter_loaders(self, template):80 loader = self.app.jinja_loader81 if loader is not None:68- yield loader, template82+ yield self.app, loader83 84 for blueprint in itervalues(self.app.blueprints):85 loader = blueprint.jinja_loader86 if loader is not None:73- yield loader, template87+ yield blueprint, loader88 89 def list_templates(self):90 result = set()91 loader = self.app.jinja_loader48 unmodified linesmodified:flask/wrappers.py+1 added-1 removed
10 unmodified lines11 12 from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13 from werkzeug.exceptions import BadRequest14 15-from .debughelpers import attach_enctype_error_multidict15 from . import json16 from .globals import _request_ctx_stack17 18 163 unmodified lines182 # 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)188 189 190 class Response(ResponseBase):9 unmodified linesmodified:CHANGES+3 added
39 unmodified lines40 - 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.47 48 Version 0.10.249 --------------50 478 unmodified lines