Skip to content
Myr

Modules are now instanciated with the package name.

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

This makes it possible to load resources from the folder the module is located in.

authored by Armin Ronacher · committed by Armin Ronacher · parent 2f181e1 · Browse files · 2 files+96 added−73 removed
This commit

State

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

Diff stats

2 files+96 added−73 removed

  • tests:+2 added−2 removed
  • other:+94 added−71 removed

2 files+96 added−73 removed

modified:tests/flask_tests.py+2 added-2 removed
300 unmodified lines
301class ModuleTestCase(unittest.TestCase):302303 def test_basic_module(self):304 app = flask.Flask(__name__)305 admin = flask.Module('admin', url_prefix='/admin')305 admin = flask.Module(__name__, 'admin', url_prefix='/admin')306 @admin.route('/')307 def index():308 return 'admin index'309 @admin.route('/login')
14 unmodified lines
324325 def test_request_processing(self):326 catched = []327 app = flask.Flask(__name__)328 admin = flask.Module('admin', url_prefix='/admin')328 admin = flask.Module(__name__, 'admin', url_prefix='/admin')329 @admin.before_request330 def before_admin_request():331 catched.append('before-admin')332 @admin.after_request
45 unmodified lines
modified:flask.py+94 added-71 removed
293 unmodified lines
294else:295 _tojson_filter = json.dumps296297298class _PackageBoundObject(object):299300 def __init__(self, import_name):301 #: the name of the package or module. Do not change this once302 #: it was set by the constructor.303 self.import_name = import_name304305 #: where is the app root located?306 self.root_path = _get_package_path(self.import_name)307308 def open_resource(self, resource):309 """Opens a resource from the application's resource folder. To see310 how this works, consider the following folder structure::311312 /myapplication.py313 /schemal.sql314 /static315 /style.css316 /template317 /layout.html318 /index.html319320 If you want to open the `schema.sql` file you would do the321 following::322323 with app.open_resource('schema.sql') as f:324 contents = f.read()325 do_something_with(contents)326327 :param resource: the name of the resource. To access resources within328 subfolders use forward slashes as separator.329 """330 if pkg_resources is None:331 return open(os.path.join(self.root_path, resource), 'rb')332 return pkg_resources.resource_stream(self.import_name, resource)333334335class _ModuleSetupState(object):336337 def __init__(self, app, url_prefix=None):338 self.app = app339 self.url_prefix = url_prefix340341305class Module(object):342class Module(_PackageBoundObject):343 """Container object that enables pluggable applications"""344308 def __init__(self, name, url_prefix=None):345 def __init__(self, import_name, name=None, url_prefix=None):346 if name is None:347 assert '.' in import_name, 'name required if package name ' \348 'does not point to a submodule'349 name = import_name.rsplit('.', 1)[1]350 _PackageBoundObject.__init__(self, import_name)351 self.name = name352 self.url_prefix = url_prefix353 self._register_events = []354355 def route(self, rule, **options):356 """Like :meth:`flask.Flask.route` but for a module"""357 def decorator(f):358 self.add_url_rule(rule, f.__name__, f, **options)359 return f360 return decorator361362 def add_url_rule(self, rule, endpoint, view_func=None, **options):320 self._record(self._register_rule, (rule, endpoint, view_func, options))363 """Like :meth:`flask.Flask.add_url_rule` but for a module"""364 def register_rule(state):365 the_rule = rule366 if self.url_prefix:367 the_rule = state.url_prefix + rule368 state.app.add_url_rule(the_rule, '%s.%s' % (self.name, endpoint),369 view_func, **options)370 self._record(register_rule)371372 def before_request(self, f):373 """Like :meth:`flask.Flask.before_request` but for a module"""374 self._record(lambda s: s.app.before_request_funcs324 .setdefault(self.name, []).append(f), ())375 .setdefault(self.name, []).append(f))376 return f377378 def after_request(self, f):379 """Like :meth:`flask.Flask.after_request` but for a module"""380 self._record(lambda s: s.app.after_request_funcs329 .setdefault(self.name, []).append(f), ())381 .setdefault(self.name, []).append(f))382 return f383332 def _record(self, func, args):333 self._register_events.append((func, args))384 def _record(self, func):385 self._register_events.append(func)386335 def _register_rule(self, state, rule, endpoint, view_func, options):336 if self.url_prefix:337 rule = state.url_prefix + rule338 state.app.add_url_rule(rule, '%s.%s' % (self.name, endpoint),339 view_func, **options)387341342class Flask(object):388class Flask(_PackageBoundObject):389 """The flask object implements a WSGI application and acts as the central390 object. It is passed the name of the module or package of the391 application. Once it is created it will act as a central registry for392 the view functions, the URL rules, template configuration and much more.
38 unmodified lines
431 autoescape=True,432 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']433 )434389 def __init__(self, package_name):435 def __init__(self, import_name):436 _PackageBoundObject.__init__(self, import_name)437438 #: the debug flag. Set this to `True` to enable debugging of439 #: the application. In debug mode the debugger will kick in440 #: when an unhandled exception ocurrs and the integrated server441 #: will automatically reload the application if changes in the442 #: code are detected.443 self.debug = False444397 #: the name of the package or module. Do not change this once398 #: it was set by the constructor.399 self.package_name = package_name400401 #: where is the app root located?402 self.root_path = _get_package_path(self.package_name)403445 #: a dictionary of all view functions registered. The keys will446 #: be function names which are also used to generate URLs and447 #: the values are the function objects themselves.448 #: to register a view function, use the :meth:`route` decorator.
5 unmodified lines
454 #: To register a error handler, use the :meth:`errorhandler`455 #: decorator.456 self.error_handlers = {}457417 #: a list of functions that should be called at the beginning418 #: of the request before request dispatching kicks in. This419 #: can for example be used to open database connections or420 #: getting hold of the currently logged in user.421 #: To register a function here, use the :meth:`before_request`422 #: decorator.458 #: a dictionary with lists of functions that should be called at the459 #: beginning of the request. The key of the dictionary is the name of460 #: the module this function is active for, `None` for all requests.461 #: This can for example be used to open database connections or462 #: getting hold of the currently logged in user. To register a463 #: function here, use the :meth:`before_request` decorator.464 self.before_request_funcs = {}465425 #: a list of functions that are called at the end of the426 #: request. The function is passed the current response427 #: object and modify it in place or replace it.428 #: To register a function here use the :meth:`after_request`429 #: decorator.466 #: a dictionary with lists of functions that should be called after467 #: each request. The key of the dictionary is the name of the module468 #: this function is active for, `None` for all requests. This can for469 #: example be used to open database connections or getting hold of the470 #: currently logged in user. To register a function here, use the471 #: :meth:`before_request` decorator.472 self.after_request_funcs = {}473432 #: a list of functions that are called without arguments433 #: to populate the template context. Each returns a dictionary434 #: that the template context is updated with.435 #: To register a function here, use the :meth:`context_processor`436 #: decorator.437 self.template_context_processors = [_default_template_ctx_processor]474 #: a dictionary with list of functions that are called without arguments475 #: to populate the template context. They key of the dictionary is the476 #: name of the module this function is active for, `None` for all477 #: requests. Each returns a dictionary that the template context is478 #: updated with. To register a function here, use the479 #: :meth:`context_processor` decorator.480 self.template_context_processors = {481 None: [_default_template_ctx_processor]482 }483484 #: the :class:`~werkzeug.routing.Map` for this instance. You can use485 #: this to change the routing converters after the class was created486 #: but before any routes are connected. Example::
14 unmodified lines
501 if self.static_path is not None:502 self.add_url_rule(self.static_path + '/<filename>',503 build_only=True, endpoint='static')504 if pkg_resources is not None:460 target = (self.package_name, 'static')505 target = (self.import_name, 'static')506 else:507 target = os.path.join(self.root_path, 'static')508 self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {509 self.static_path: target
17 unmodified lines
527 override this method.528 """529 if pkg_resources is None:530 return FileSystemLoader(os.path.join(self.root_path, 'templates'))486 return PackageLoader(self.package_name)531 return PackageLoader(self.import_name)532533 def update_template_context(self, context):534 """Update the template context with some commonly used variables.535 This injects request, session and g into the template context.536537 :param context: the context as a dictionary that is updated in place538 to add extra variables.539 """540 funcs = self.template_context_processors[None]541 mod = _request_ctx_stack.top.request.module495 for func in self.template_context_processors:542 if mod is not None and mod in self.template_context_processors:543 funcs = chain(funcs, self.template_context_processors[mod])544 for func in funcs:545 context.update(func())546547 def run(self, host='127.0.0.1', port=5000, **options):548 """Runs the application on a local development server. If the
20 unmodified lines
569 """570 from werkzeug import Client571 return Client(self, self.response_class, use_cookies=True)572524 def open_resource(self, resource):525 """Opens a resource from the application's resource folder. To see526 how this works, consider the following folder structure::527528 /myapplication.py529 /schemal.sql530 /static531 /style.css532 /template533 /layout.html534 /index.html535536 If you want to open the `schema.sql` file you would do the537 following::538539 with app.open_resource('schema.sql') as f:540 contents = f.read()541 do_something_with(contents)542543 :param resource: the name of the resource. To access resources within544 subfolders use forward slashes as separator.545 """546 if pkg_resources is None:547 return open(os.path.join(self.root_path, resource), 'rb')548 return pkg_resources.resource_stream(self.package_name, resource)549573 def open_session(self, request):574 """Creates or opens a new session. Default implementation stores all575 session data in a signed cookie. This requires that the576 :attr:`secret_key` is set.
19 unmodified lines
596 def register_module(self, module, **options):597 """Registers a module with this application."""598 options.setdefault('url_prefix', module.url_prefix)599 state = _ModuleSetupState(self, **options)577 for func, args in module._register_events:578 func(state, *args)600 for func in module._register_events:601 func(state)602603 def add_url_rule(self, rule, endpoint=None, view_func=None, **options):604 """Connects a URL rule. Works exactly like the :meth:`route`605 decorator. If a view_func is provided it will be registered with the
142 unmodified lines
748 return f749750 def context_processor(self, f):751 """Registers a template context processor function."""729 self.template_context_processors.append(f)752 self.template_context_processors[None].append(f)753 return f754755 def dispatch_request(self):756 """Does the request dispatching. Matches the URL and returns the
146 unmodified lines