Added support for loading templates from modules
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 15012af · Browse files · 3 files·+72 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+72 added−30 removed
- other:+72 added−30 removed
Provenance
- Commit
a38dcd5- Tree
6691e40- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
15012af
3 files changed+72 added−30 removed
modified:flask/app.py+52 added-20 removed
12 unmodified lines13 from threading import Lock14 from datetime import timedelta, datetime15 from itertools import chain16 17-from jinja2 import Environment, PackageLoader, FileSystemLoader17+from jinja2 import Environment, BaseLoader, FileSystemLoader, TemplateNotFound18 from werkzeug import ImmutableDict, create_environ19 from werkzeug.routing import Map, Rule20 from werkzeug.exceptions import HTTPException, InternalServerError, NotFound21 9 unmodified lines31 # a lock used for logger initialization32 _logger_lock = Lock()33 34 35-def _select_autoescape(filename):36- """Returns `True` if autoescaping should be active for the given37- template name.35+class _DispatchingJinjaLoader(BaseLoader):36+ """A loader that looks for templates in the application and all37+ the module folders.38 """39- if filename is None:40- return False41- return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))39 40+ def __init__(self, app):41+ self.app = app42 43+ def get_source(self, environment, template):44+ name = template45+ loader = None46+ try:47+ module, name = template.split('/', 1)48+ loader = self.app.modules[module].jinja_loader49+ except (ValueError, KeyError):50+ pass51+ if loader is None:52+ loader = self.app.jinja_loader53+ try:54+ return loader.get_source(environment, name)55+ except TemplateNotFound:56+ # re-raise the exception with the correct fileame here.57+ # (the one that includes the prefix)58+ raise TemplateNotFound(template)59+60+ def list_templates(self):61+ result = self.app.jinja_loader.list_templates()62+ for name, module in self.app.modules.iteritems():63+ if module.jinja_loader is not None:64+ for template in module.jinja_loader.list_templates():65+ result.append('%s/%s' % (name, template))66+ return result67+68+69 class Flask(_PackageBoundObject):70 """The flask object implements a WSGI application and acts as the central71 object. It is passed the name of the module or package of the72 application. Once it is created it will act as a central registry for127 unmodified lines200 )201 202 #: Options that are passed directly to the Jinja2 environment.203 jinja_options = ImmutableDict(179- autoescape=_select_autoescape,204 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']205 )206 207 #: Default configuration parameters.60 unmodified lines268 self.template_context_processors = {269 None: [_default_template_ctx_processor]270 }271 272+ #: all the loaded modules in a dictionary by name.273+ #:274+ #: .. versionadded:: 0.5275+ self.modules = {}276+277 #: The :class:`~werkzeug.routing.Map` for this instance. You can use278 #: this to change the routing converters after the class was created279 #: but before any routes are connected. Example::280 #:16 unmodified lines297 endpoint='static',298 view_func=self.send_static_file)299 300 #: The Jinja2 environment. It is created from the272- #: :attr:`jinja_options` and the loader that is returned273- #: by the :meth:`create_jinja_loader` function.301+ #: :attr:`jinja_options`.302 self.jinja_env = self.create_jinja_environment()303 self.init_jinja_globals()304 305 @property36 unmodified lines342 and :meth:`create_jinja_loader`.343 344 .. versionadded:: 0.5345 """318- return Environment(loader=self.create_jinja_loader(),319- **self.jinja_options)346+ options = dict(self.jinja_options)347+ if 'autoescape' not in options:348+ options['autoescape'] = self.select_jinja_autoescape349+ return Environment(loader=_DispatchingJinjaLoader(self), **options)350 321- def create_jinja_loader(self):322- """Creates the Jinja loader. By default just a package loader for323- the configured package is returned that looks up templates in the324- `templates` folder. To add other loaders it's possible to325- override this method.326- """327- return FileSystemLoader(os.path.join(self.root_path, 'templates'))328-351 def init_jinja_globals(self):352 """Called directly after the environment was created to inject353 some defaults (like `url_for`, `get_flashed_messages` and the354 `tojson` filter.5 unmodified lines360 get_flashed_messages=get_flashed_messages361 )362 self.jinja_env.filters['tojson'] = _tojson_filter363 364+ def select_jinja_autoescape(self, filename):365+ """Returns `True` if autoescaping should be active for the given366+ template name.367+368+ .. versionadded:: 0.5369+ """370+ if filename is None:371+ return False372+ return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))373+374 def update_template_context(self, context):375 """Update the template context with some commonly used variables.376 This injects request, session and g into the template context.377 489 unmodified linesmodified:flask/helpers.py+13 added-1 removed
25 unmodified lines26 import json27 except ImportError:28 json_available = False29 30-from werkzeug import Headers, wrap_file, is_resource_modified30+from werkzeug import Headers, wrap_file, is_resource_modified, cached_property31 32+from jinja2 import FileSystemLoader33+34 from flask.globals import session, _request_ctx_stack, current_app, request35 from flask.wrappers import Response36 37 303 unmodified lines341 .. versionadded:: 0.5342 """343 return os.path.isdir(os.path.join(self.root_path, 'static'))344 345+ @cached_property346+ def jinja_loader(self):347+ """The Jinja loader for this package bound object.348+349+ .. versionadded:: 0.5350+ """351+ template_folder = os.path.join(self.root_path, 'templates')352+ if os.path.isdir(template_folder):353+ return FileSystemLoader(template_folder)354+355 def send_static_file(self, filename):356 """Function used internally to send static files from the static357 folder to the browser.358 33 unmodified linesmodified:flask/module.py+7 added-9 removed
10 unmodified lines11 12 from flask.helpers import _PackageBoundObject13 14 15-def _register_module_static(module):15+def _register_module(module):16 """Internal helper function that returns a function for recording17 that registers the `send_static_file` function for the module on18- the application of necessary.18+ the application of necessary. It also registers the module on19+ the application.20 """20- def _register_static(state):21+ def _register(state):22+ state.app.modules[module.name] = module23 # do not register the rule if the static folder of the24 # module is the same as the one from the application.25 if state.app.root_path == module.root_path:26 return4 unmodified lines31 path = state.url_prefix + path32 state.app.add_url_rule(path + '/<filename>',33 '%s.static' % module.name,34 view_func=module.send_static_file)33- return _register_static35+ return _register36 37 38 class _ModuleSetupState(object):39 58 unmodified lines98 name = import_name.rsplit('.', 1)[1]99 _PackageBoundObject.__init__(self, import_name)100 self.name = name101 self.url_prefix = url_prefix100- self._register_events = []102+ self._register_events = [_register_module(self)]103 102- # if there is a static folder, register it for this module103- if self.has_static_folder:104- self._record(_register_module_static(self))105-104 def route(self, rule, **options):105 """Like :meth:`Flask.route` but for a module. The endpoint for the106 :func:`url_for` function is prefixed with the name of the module.107 """80 unmodified lines