Skip to content
Myr

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

3 files+72 added−30 removed

modified:flask/app.py+52 added-20 removed
12 unmodified lines
13from threading import Lock14from datetime import timedelta, datetime15from itertools import chain1617from jinja2 import Environment, PackageLoader, FileSystemLoader17from jinja2 import Environment, BaseLoader, FileSystemLoader, TemplateNotFound18from werkzeug import ImmutableDict, create_environ19from werkzeug.routing import Map, Rule20from werkzeug.exceptions import HTTPException, InternalServerError, NotFound21
9 unmodified lines
31# a lock used for logger initialization32_logger_lock = Lock()333435def _select_autoescape(filename):36 """Returns `True` if autoescaping should be active for the given37 template name.35class _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'))3940 def __init__(self, app):41 self.app = app4243 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)5960 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 result676869class 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 for
127 unmodified lines
200 )201202 #: 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 )206207 #: Default configuration parameters.
60 unmodified lines
268 self.template_context_processors = {269 None: [_default_template_ctx_processor]270 }271272 #: all the loaded modules in a dictionary by name.273 #:274 #: .. versionadded:: 0.5275 self.modules = {}276277 #: 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 lines
297 endpoint='static',298 view_func=self.send_static_file)299300 #: 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()304305 @property
36 unmodified lines
342 and :meth:`create_jinja_loader`.343344 .. 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)350321 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'))328351 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 lines
360 get_flashed_messages=get_flashed_messages361 )362 self.jinja_env.filters['tojson'] = _tojson_filter363364 def select_jinja_autoescape(self, filename):365 """Returns `True` if autoescaping should be active for the given366 template name.367368 .. versionadded:: 0.5369 """370 if filename is None:371 return False372 return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))373374 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 lines
modified:flask/helpers.py+13 added-1 removed
25 unmodified lines
26 import json27 except ImportError:28 json_available = False2930from werkzeug import Headers, wrap_file, is_resource_modified30from werkzeug import Headers, wrap_file, is_resource_modified, cached_property3132from jinja2 import FileSystemLoader3334from flask.globals import session, _request_ctx_stack, current_app, request35from flask.wrappers import Response3637
303 unmodified lines
341 .. versionadded:: 0.5342 """343 return os.path.isdir(os.path.join(self.root_path, 'static'))344345 @cached_property346 def jinja_loader(self):347 """The Jinja loader for this package bound object.348349 .. 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)354355 def send_static_file(self, filename):356 """Function used internally to send static files from the static357 folder to the browser.358
33 unmodified lines
modified:flask/module.py+7 added-9 removed
10 unmodified lines
1112from flask.helpers import _PackageBoundObject131415def _register_module_static(module):15def _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 return
4 unmodified lines
31 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 _register363738class _ModuleSetupState(object):39
58 unmodified lines
98 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)]103102 # if there is a static folder, register it for this module103 if self.has_static_folder:104 self._record(_register_module_static(self))105104 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