From 745638e774063de206aae930df71789de13e7c73 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Tue, 4 May 2010 11:51:07 +0200 Subject: [PATCH] Added missing decorators for module wide context processors. This fixes #25. --- flask.py | 20 ++++++++++++++++++-- tests/flask_tests.py | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/flask.py b/flask.py index 1d0fa852..c5516c4f 100644 --- a/flask.py +++ b/flask.py @@ -465,7 +465,7 @@ class Module(_PackageBoundObject): def before_app_request(self, f): """Like :meth:`Flask.before_request`. Such a function is executed - before each request. + before each request, even if outside of a module. """ self._record(lambda s: s.app.before_request_funcs .setdefault(None, []).append(f)) @@ -482,12 +482,28 @@ class Module(_PackageBoundObject): def after_app_request(self, f): """Like :meth:`Flask.after_request` but for a module. Such a function - is executed after each request. + is executed after each request, even if outside of the module. """ self._record(lambda s: s.app.after_request_funcs .setdefault(None, []).append(f)) return f + def context_processor(self, f): + """Like :meth:`Flask.context_processor` but for a modul. This + function is only executed for requests handled by a module. + """ + self._record(lambda s: s.app.template_context_processors + .setdefault(self.name, []).append(f)) + return f + + def app_context_processor(self, f): + """Like :meth:`Flask.context_processor` but for a module. Such a + function is executed each request, even if outside of the module. + """ + self._record(lambda s: s.app.template_context_processors + .setdefault(None, []).append(f)) + return f + def _record(self, func): self._register_events.append(func) diff --git a/tests/flask_tests.py b/tests/flask_tests.py index 8b3f7640..1240dadd 100644 --- a/tests/flask_tests.py +++ b/tests/flask_tests.py @@ -441,6 +441,29 @@ class ModuleTestCase(unittest.TestCase): assert catched == ['before-app', 'before-admin', 'after-admin', 'after-app'] + def test_context_processors(self): + app = flask.Flask(__name__) + admin = flask.Module(__name__, 'admin', url_prefix='/admin') + @app.context_processor + def inject_all_regualr(): + return {'a': 1} + @admin.context_processor + def inject_admin(): + return {'b': 2} + @admin.app_context_processor + def inject_all_module(): + return {'c': 3} + @app.route('/') + def index(): + return flask.render_template_string('{{ a }}{{ b }}{{ c }}') + @admin.route('/') + def index(): + return flask.render_template_string('{{ a }}{{ b }}{{ c }}') + app.register_module(admin) + c = app.test_client() + assert c.get('/').data == '13' + assert c.get('/admin/').data == '123' + def test_late_binding(self): app = flask.Flask(__name__) admin = flask.Module(__name__, 'admin')