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
Provenance
- Commit
a06cd0a- Tree
d6682e8- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1446614
4 files changed+93 added−22 removed
modified:flask/app.py+27 added-5 removed
14 unmodified lines15 from threading import Lock16 from datetime import timedelta, datetime17 from itertools import chain18 19-from jinja2 import Environment20-19 from werkzeug import ImmutableDict20 from werkzeug.routing import Map, Rule21 from werkzeug.exceptions import HTTPException, InternalServerError, \22 MethodNotAllowed5 unmodified lines28 from .ctx import _RequestContext29 from .globals import _request_ctx_stack, request30 from .session import Session, _NullSession31 from .module import _ModuleSetupState34-from .templating import _DispatchingJinjaLoader, \32+from .templating import DispatchingJinjaLoader, Environment, \33 _default_template_ctx_processor34 from .signals import request_started, request_finished, got_request_exception35 36 # a lock used for logger initialization240 unmodified lines277 #:278 #: .. versionadded:: 0.5279 self.modules = {}280 281+ #: 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 = {}287+288 #: 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 lines390 """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 lines404 override just the loader and keeping the rest unchanged.405 406 .. versionadded:: 0.7407 """403- return _DispatchingJinjaLoader(self)408+ return DispatchingJinjaLoader(self)409 410 def init_jinja_globals(self):411 """Deprecated. Used to initialize the Jinja2 globals.412 128 unmodified lines541 """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.545+546+ .. 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 lines565 state = _ModuleSetupState(self, **options)566 for func in module._register_events:567 func(state)568 569+ def register_blueprint(self, blueprint, **options):570+ """Registers a blueprint on the application.571+572+ .. 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)581+582 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 linesmodified:flask/templating.py+56 added-16 removed
7 unmodified lines8 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import posixpath12-from jinja2 import BaseLoader, TemplateNotFound12+from jinja2 import BaseLoader, Environment as BaseEnvironment, \13+ TemplateNotFound14 15 from .globals import _request_ctx_stack16 from .signals import template_rendered17 10 unmodified lines28 g=reqctx.g29 )30 31 32+class 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+ """37+38+ 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 = app43+44+ def join_path(self, template, parent):45+ if template and template[0] == ':':46+ template = parent.split(':', 1)[0] + template47+ return template48+49+31-class _DispatchingJinjaLoader(BaseLoader):50+class DispatchingJinjaLoader(BaseLoader):51 """A loader that looks for templates in the application and all52 the module folders.53 """54 55 def __init__(self, app):56 self.app = app57 58 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)71+72+ # 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+ pass85+86+ # at the very last, load templates from the environment87 return self.app.jinja_loader.get_source(environment, template)88 89 def list_templates(self):59- result = self.app.jinja_loader.list_templates()90+ result = set(self.app.jinja_loader.list_templates())91+92 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))96 97+ 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))101 102+ return list(result)103+104+105 def _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 lines118 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)126 127 13 unmodified linesmodified:flask/wrappers.py+9 added-1 removed
60 unmodified lines61 62 @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]69 70+ @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]75+76 @cached_property77 def json(self):78 """If the mimetype is `application/json` this will contain the79 parsed JSON data.17 unmodified linesmodified:tests/flask_tests.py+1 added
1109 unmodified lines1110 assert 'internal server error' == rv.data1111 1112 def test_templates_and_static(self):1113 app = moduleapp1114+ app.debug = True1115 c = app.test_client()1116 1117 rv = c.get('/')1118 assert rv.data == 'Hello from the Frontend'518 unmodified lines