Skip to content
Myr

Started work on implementing blueprint based template loading

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 1446614 · Browse files · 4 files+93 added−22 removed
This commit

State

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

Diff stats

4 files+93 added−22 removed

  • tests:+1 added−0 removed
  • other:+92 added−22 removed

4 files+93 added−22 removed

modified:flask/app.py+27 added-5 removed
14 unmodified lines
15from threading import Lock16from datetime import timedelta, datetime17from itertools import chain1819from jinja2 import Environment2019from werkzeug import ImmutableDict20from werkzeug.routing import Map, Rule21from werkzeug.exceptions import HTTPException, InternalServerError, \22 MethodNotAllowed
5 unmodified lines
28from .ctx import _RequestContext29from .globals import _request_ctx_stack, request30from .session import Session, _NullSession31from .module import _ModuleSetupState34from .templating import _DispatchingJinjaLoader, \32from .templating import DispatchingJinjaLoader, Environment, \33 _default_template_ctx_processor34from .signals import request_started, request_finished, got_request_exception3536# a lock used for logger initialization
240 unmodified lines
277 #:278 #: .. versionadded:: 0.5279 self.modules = {}280281 #: all the attached blueprints in a directory by name. Blueprints282 #: can be attached multiple times so this dictionary does not tell283 #: you how often they got attached.284 #:285 #: .. versionadded:: 0.7286 self.blueprints = {}287288 #: a place where extensions can store application specific state. For289 #: example this is where an extension could store database engines and290 #: similar things. For backwards compatibility extensions should register291 #: themselves like this::
98 unmodified lines
390 """391 options = dict(self.jinja_options)392 if 'autoescape' not in options:393 options['autoescape'] = self.select_jinja_autoescape389 rv = Environment(loader=self.create_jinja_loader(), **options)394 rv = Environment(self, **options)395 rv.globals.update(396 url_for=url_for,397 get_flashed_messages=get_flashed_messages398 )
5 unmodified lines
404 override just the loader and keeping the rest unchanged.405406 .. versionadded:: 0.7407 """403 return _DispatchingJinjaLoader(self)408 return DispatchingJinjaLoader(self)409410 def init_jinja_globals(self):411 """Deprecated. Used to initialize the Jinja2 globals.412
128 unmodified lines
541 """Registers a module with this application. The keyword argument542 of this function are the same as the ones for the constructor of the543 :class:`Module` class and will override the values of the module if544 provided.545546 .. versionchanged:: 0.7547 The module system was deprecated in favor for the blueprint548 system.549 """550 if not self.enable_modules:551 raise RuntimeError('Module support was disabled but code '552 'attempted to register a module named %r' % module)
12 unmodified lines
565 state = _ModuleSetupState(self, **options)566 for func in module._register_events:567 func(state)568569 def register_blueprint(self, blueprint, **options):570 """Registers a blueprint on the application.571572 .. versionadded:: 0.7573 """574 if blueprint.name in self.blueprints:575 assert self.blueprints[blueprint.name] is blueprint, \576 'A blueprint\'s name collision ocurred between %r and ' \577 '%r.' % (blueprint, self.blueprints[blueprint.name])578 else:579 self.blueprints[blueprint.name] = blueprint580 blueprint.register(self, **options)581582 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):583 """Connects a URL rule. Works exactly like the :meth:`route`584 decorator. If a view_func is provided it will be registered with the585 endpoint.
486 unmodified lines
modified:flask/templating.py+56 added-16 removed
7 unmodified lines
8 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import posixpath12from jinja2 import BaseLoader, TemplateNotFound12from jinja2 import BaseLoader, Environment as BaseEnvironment, \13 TemplateNotFound1415from .globals import _request_ctx_stack16from .signals import template_rendered17
10 unmodified lines
28 g=reqctx.g29 )303132class Environment(BaseEnvironment):33 """Works like a regular Jinja2 environment but has some additional34 knowledge of how Flask's blueprint works so that it can prepend the35 name of the blueprint to referenced templates if necessary.36 """3738 def __init__(self, app, **options):39 if 'loader' not in options:40 options['loader'] = app.create_jinja_loader()41 BaseEnvironment.__init__(self, **options)42 self.app = app4344 def join_path(self, template, parent):45 if template and template[0] == ':':46 template = parent.split(':', 1)[0] + template47 return template484931class _DispatchingJinjaLoader(BaseLoader):50class DispatchingJinjaLoader(BaseLoader):51 """A loader that looks for templates in the application and all52 the module folders.53 """5455 def __init__(self, app):56 self.app = app5758 def get_source(self, environment, template):40 template = posixpath.normpath(template)41 if template.startswith('../'):42 raise TemplateNotFound(template)59 # newstyle template support. blueprints are explicit and no further60 # magic is involved. If the template cannot be loaded by the61 # blueprint loader it just gives up, no further steps involved.62 if ':' in template:63 blueprint_name, local_template = template.split(':', 1)64 local_template = posixpath.normpath(local_template)65 blueprint = self.app.blueprints.get(blueprint_name)66 if blueprint is None:67 raise TemplateNotFound(template)68 loader = blueprint.jinja_loader69 if loader is not None:70 return loader.get_source(environment, local_template)7172 # if modules are enabled we call into the old style template lookup73 # and try that before we go with the real deal.74 loader = None75 try:45 module, name = template.split('/', 1)76 module, name = posixpath.normpath(template).split('/', 1)77 loader = self.app.modules[module].jinja_loader47 except (ValueError, KeyError):78 except (ValueError, KeyError, TemplateNotFound):79 pass49 # if there was a module and it has a loader, try this first50 if loader is not None:51 try:80 try:81 if loader is not None:82 return loader.get_source(environment, name)53 except TemplateNotFound:54 pass55 # fall back to application loader if module failed83 except TemplateNotFound:84 pass8586 # at the very last, load templates from the environment87 return self.app.jinja_loader.get_source(environment, template)8889 def list_templates(self):59 result = self.app.jinja_loader.list_templates()90 result = set(self.app.jinja_loader.list_templates())9192 for name, module in self.app.modules.iteritems():93 if module.jinja_loader is not None:94 for template in module.jinja_loader.list_templates():63 result.append('%s/%s' % (name, template))64 return result95 result.add('%s/%s' % (name, template))9697 for name, blueprint in self.app.blueprints.iteritems():98 if blueprint.jinja_loader is not None:99 for template in blueprint.jinja_loader.list_templates():100 result.add('%s:%s' % (name, template))101102 return list(result)103104105def _render(template, context, app):106 """Renders the template and fires the signal"""107 rv = template.render(context)108 template_rendered.send(app, template=template, context=context)
9 unmodified lines
118 context of the template.119 """120 ctx = _request_ctx_stack.top121 ctx.app.update_template_context(context)122 if template_name[:1] == ':':123 template_name = ctx.request.blueprint + template_name124 return _render(ctx.app.jinja_env.get_template(template_name),125 context, ctx.app)126127
13 unmodified lines
modified:flask/wrappers.py+9 added-1 removed
60 unmodified lines
6162 @property63 def module(self):64 """The name of the current module"""65 if self.url_rule and '.' in self.url_rule.endpoint:65 if self.url_rule and \66 ':' not in self.url_rule.endpoint and \67 '.' in self.url_rule.endpoint:68 return self.url_rule.endpoint.rsplit('.', 1)[0]6970 @property71 def blueprint(self):72 """The name of the current blueprint"""73 if self.url_rule and ':' in self.url_rule.endpoint:74 return self.url_rule.endpoint.split(':', 1)[0]7576 @cached_property77 def json(self):78 """If the mimetype is `application/json` this will contain the79 parsed JSON data.
17 unmodified lines
modified:tests/flask_tests.py+1 added
1109 unmodified lines
1110 assert 'internal server error' == rv.data11111112 def test_templates_and_static(self):1113 app = moduleapp1114 app.debug = True1115 c = app.test_client()11161117 rv = c.get('/')1118 assert rv.data == 'Hello from the Frontend'
518 unmodified lines