Refactored static folder registration
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 fedc06c · Browse files · 3 files·+60 added−19 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+60 added−19 removed
- other:+60 added−19 removed
Provenance
- Commit
15012af- Tree
6b9b3b0- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
fedc06c
3 files changed+60 added−19 removed
modified:flask/app.py+9 added-18 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 import os13-import posixpath13 from threading import Lock14 from datetime import timedelta, datetime15 from itertools import chain16 2 unmodified lines19 from werkzeug.routing import Map, Rule20 from werkzeug.exceptions import HTTPException, InternalServerError, NotFound21 22 from flask.helpers import _PackageBoundObject, url_for, get_flashed_messages, \24- _tojson_filter, send_file23+ _tojson_filter24 from flask.wrappers import Request, Response25 from flask.config import ConfigAttribute, Config26 from flask.ctx import _default_template_ctx_processor, _RequestContext27 from flask.globals import _request_ctx_stack, request71 unmodified lines99 100 #: Path for the static files. If you don't want to use static files101 #: you can set this value to `None` in which case no URL rule is added102 #: and the development server will no longer serve any static files.103+ #:104+ #: This is the default used for application and modules unless a105+ #: different value is passed to the constructor.106 static_path = '/static'107 108 #: The debug flag. Set this to `True` to enable debugging of the109 #: application. In debug mode the debugger will kick in when an unhandled81 unmodified lines191 'LOGGER_NAME': None,192 'SERVER_NAME': None193 })194 193- def __init__(self, import_name):195+ def __init__(self, import_name, static_path=None):196 _PackageBoundObject.__init__(self, import_name)197+ if static_path is not None:198+ self.static_path = static_path199 200 #: The configuration dictionary as :class:`Config`. This behaves201 #: exactly like a regular dictionary but supports additional methods202 #: to load a config from files.58 unmodified lines261 #: app = Flask(__name__)262 #: app.url_map.converters['list'] = ListConverter263 self.url_map = Map()264 261- if self.static_path is not None:265+ # if there is a static folder, register it for the application.266+ if self.has_static_folder:267 self.add_url_rule(self.static_path + '/<filename>',268 endpoint='static',269 view_func=self.send_static_file)270 110 unmodified lines381 options.setdefault('use_reloader', self.debug)382 options.setdefault('use_debugger', self.debug)383 return run_simple(host, port, self, **options)384 380- def send_static_file(self, filename):381- """Function used internally to send static files from the static382- folder to the browser.383-384- .. versionadded:: 0.5385- """386- filename = posixpath.normpath(filename)387- if filename.startswith('../'):388- raise NotFound()389- filename = os.path.join(self.root_path, 'static', filename)390- if not os.path.isfile(filename):391- raise NotFound()392- return send_file(filename, conditional=True)393-385 def test_client(self):386 """Creates a test client for this application. For information387 about unit testing head over to :ref:`testing`.388 446 unmodified linesmodified:flask/helpers.py+24 added
9 unmodified lines10 """11 12 import os13 import sys14+import posixpath15 import mimetypes16 from time import time17 from zlib import adler3218 311 unmodified lines330 331 #: Where is the app root located?332 self.root_path = _get_package_path(self.import_name)333 334+ @property335+ def has_static_folder(self):336+ """This is `True` if the package bound object's container has a337+ folder named ``'static'``.338+339+ .. versionadded:: 0.5340+ """341+ return os.path.isdir(os.path.join(self.root_path, 'static'))342+343+ def send_static_file(self, filename):344+ """Function used internally to send static files from the static345+ folder to the browser.346+347+ .. versionadded:: 0.5348+ """349+ filename = posixpath.normpath(filename)350+ if filename.startswith('../'):351+ raise NotFound()352+ filename = os.path.join(self.root_path, 'static', filename)353+ if not os.path.isfile(filename):354+ raise NotFound()355+ return send_file(filename, conditional=True)356+357 def open_resource(self, resource):358 """Opens a resource from the application's resource folder. To see359 how this works, consider the following folder structure::360 19 unmodified linesmodified:flask/module.py+27 added-1 removed
10 unmodified lines11 12 from flask.helpers import _PackageBoundObject13 14 15+def _register_module_static(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.19+ """20+ def _register_static(state):21+ # do not register the rule if the static folder of the22+ # module is the same as the one from the application.23+ if state.app.root_path == module.root_path:24+ return25+ path = static_path26+ if path is None:27+ path = state.app.static_path28+ if state.url_prefix:29+ path = state.url_prefix + path30+ state.app.add_url_rule(path + '/<filename>',31+ '%s.static' % module.name,32+ view_func=module.send_static_file)33+ return _register_static34+35+36 class _ModuleSetupState(object):37 38 def __init__(self, app, url_prefix=None):39 self.app = app47 unmodified lines87 For a gentle introduction into modules, checkout the88 :ref:`working-with-modules` section.89 """90 70- def __init__(self, import_name, name=None, url_prefix=None):91+ def __init__(self, import_name, name=None, url_prefix=None,92+ static_path=None):93 if name is None:94 assert '.' in import_name, 'name required if package name ' \95 'does not point to a submodule'96 name = import_name.rsplit('.', 1)[1]1 unmodified line98 self.name = name99 self.url_prefix = url_prefix100 self._register_events = []101 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+106 def route(self, rule, **options):107 """Like :meth:`Flask.route` but for a module. The endpoint for the108 :func:`url_for` function is prefixed with the name of the module.109 """80 unmodified lines