Added support for signals
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 a59dfe4 · Browse files · 10 files·+212 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+212 added−4 removed
- tests:+80 added−0 removed
- other:+132 added−4 removed
Provenance
- Commit
e0712b4- Tree
e74f822- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
a59dfe4
10 files changed+212 added−4 removed
modified:docs/api.rst+51 added
349 unmodified lines350 You might find this helpful for unittests where you need the351 information from the context local around for a little longer. Make352 sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in353 that situation, otherwise your unittests will leak memory.354+355+Signals356+-------357+358+.. versionadded:: 0.6359+360+.. data:: signals_available361+362+ `True` if the signalling system is available. This is the case363+ when `blinker`_ is installed.364+365+.. data:: template_rendered366+367+ This signal is sent when a template was successfully rendered. The368+ signal is invoked with the instance of the template as `template`369+ and the context as dictionary (named `context`).370+371+.. data:: request_started372+373+ This signal is sent before any request processing started but when the374+ request context was set up. Because the request context is already375+ bound, the subscriber can access the request with the standard global376+ proxies such as :class:`~flask.request`.377+378+.. data:: request_finished379+380+ This signal is sent right before the response is sent to the client.381+ It is passed the response to be sent named `response`.382+383+.. data:: got_request_exception384+385+ This signal is sent when an exception happens during request processing.386+ It is sent *before* the standard exception handling kicks in and even387+ in debug mode, where no exception handling happens. The exception388+ itself is passed to the subscriber as `exception`.389+390+.. class:: flask.signals.Namespace391+392+ An alias for :class:`blinker.base.Namespace` if blinker is available,393+ otherwise a dummy class that creates fake signals. This class is394+ available for Flask extensions that want to provide the same fallback395+ system as Flask itself.396+397+ .. method:: signal(name, doc=None)398+399+ Creates a new signal for this namespace if blinker is available,400+ otherwise returns a fake signal that has a send method that will401+ do nothing but will fail with a :exc:`RuntimeError` for all other402+ operations, including connecting.403+404+.. _blinker: http://pypi.python.org/pypi/blinkermodified:docs/conf.py+2 added-1 removed
243 unmodified lines244 intersphinx_mapping = {245 'http://docs.python.org/dev': None,246 'http://werkzeug.pocoo.org/documentation/dev/': None,247 'http://www.sqlalchemy.org/docs/': None,248- 'http://wtforms.simplecodes.com/docs/0.5/': None248+ 'http://wtforms.simplecodes.com/docs/0.5/': None,249+ 'http://discorporate.us/projects/Blinker/docs/1.0/': None250 }251 252 pygments_style = 'flask_theme_support.FlaskyStyle'modified:flask/__init__.py+4 added
22 unmodified lines23 from .globals import current_app, g, request, session, _request_ctx_stack24 from .module import Module25 from .templating import render_template, render_template_string26 27+# the signals28+from .signals import signals_available, template_rendered, request_started, \29+ request_finished, got_request_exception30+31 # only import json if it's available32 if json_available:33 from .helpers import jsonmodified:flask/app.py+4 added
30 unmodified lines31 from .session import Session, _NullSession32 from .module import _ModuleSetupState33 from .templating import _DispatchingJinjaLoader, \34 _default_template_ctx_processor35+from .signals import request_started, request_finished, got_request_exception36 37 # a lock used for logger initialization38 _logger_lock = Lock()39 617 unmodified lines657 exists, a default 500 internal server error message is displayed.658 659 .. versionadded: 0.3660 """661+ got_request_exception.send(self, exception=e)662 handler = self.error_handlers.get(500)663 if self.debug:664 raise665 self.logger.exception('Exception on %s [%s]' % (126 unmodified lines792 exception context to start the response793 """794 with self.request_context(environ):795 try:796+ request_started.send(self)797 rv = self.preprocess_request()798 if rv is None:799 rv = self.dispatch_request()800 response = self.make_response(rv)2 unmodified lines803 try:804 response = self.process_response(response)805 except Exception, e:806 response = self.make_response(self.handle_exception(e))807+ request_finished.send(self, response=response)808 return response(environ, start_response)809 810 def request_context(self, environ):811 """Creates a request context from the given environment and binds48 unmodified linesadded:flask/signals.py+50 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.signals4+ ~~~~~~~~~~~~~5+6+ Implements signals based on blinker if available, otherwise7+ falls silently back to a noop8+9+ :copyright: (c) 2010 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+signals_available = False13+try:14+ from blinker import Namespace15+ signals_available = True16+ _signals = Namespace()17+except ImportError:18+ class Namespace(object):19+ def signal(self, name, doc=None):20+ return _FakeSignal(name, doc)21+ class _FakeSignal(object):22+ """If blinker is unavailable, create a fake class with the same23+ interface that allows sending of signals but will fail with an24+ error on anything else. Instead of doing anything on send, it25+ will just ignore the arguments and do nothing instead.26+ """27+28+ def __init__(self, name, doc=None):29+ self.name = name30+ self.__doc__ = doc31+ def _fail(self, *args, **kwargs):32+ raise RuntimeError('signalling support is unavailable '33+ 'because the blinker library is '34+ 'not installed.')35+ send = lambda *a, **kw: None36+ connect = disconnect = has_receivers_for = receivers_for = \37+ temporarily_connected_to = _fail38+ del _fail39+40+# the namespace for code signals. If you are not flask code, do41+# not put signals in here. Create your own namespace instead.42+_signals = Namespace()43+44+45+# core signals. For usage examples grep the sourcecode or consult46+# the API documentation in docs/api.rst as well as docs/signals.rst47+template_rendered = _signals.signal('template-rendered')48+request_started = _signals.signal('request-started')49+request_finished = _signals.signal('request-finished')50+got_request_exception = _signals.signal('got-request-exception')modified:flask/templating.py+12 added-2 removed
9 unmodified lines10 """11 from jinja2 import BaseLoader, FileSystemLoader, TemplateNotFound12 13 from .globals import _request_ctx_stack14+from .signals import template_rendered15 16 17 def _default_template_ctx_processor():18 """Default template context processor. Injects `request`,40 unmodified lines59 result.append('%s/%s' % (name, template))60 return result61 62 63+def _render(template, context, app):64+ """Renders the template and fires the signal"""65+ rv = template.render(context)66+ template_rendered.send(app, template=template, context=context)67+ return rv68+69+70 def render_template(template_name, **context):71 """Renders a template from the template folder with the given72 context.73 2 unmodified lines76 context of the template.77 """78 ctx = _request_ctx_stack.top79 ctx.app.update_template_context(context)72- return ctx.app.jinja_env.get_template(template_name).render(context)80+ return _render(ctx.app.jinja_env.get_template(template_name),81+ context, ctx.app)82 83 84 def render_template_string(source, **context):85 """Renders a template from the given template source string5 unmodified lines91 context of the template.92 """93 ctx = _request_ctx_stack.top94 ctx.app.update_template_context(context)86- return ctx.app.jinja_env.from_string(source).render(context)95+ return _render(ctx.app.jinja_env.from_string(source),96+ context, ctx.app)added:tests/templates/simple_template.html+1 added
1<h1>{{ whiskey }}</h1>modified:tests/flask_tests.py+79 added
1022 unmodified lines1023 rv = c.get('/', 'http://mitsuhiko.localhost/')1024 assert rv.data == 'index for mitsuhiko'1025 1026 1027+class TestSignals(unittest.TestCase):1028+1029+ def test_template_rendered(self):1030+ app = flask.Flask(__name__)1031+1032+ @app.route('/')1033+ def index():1034+ return flask.render_template('simple_template.html', whiskey=42)1035+1036+ recorded = []1037+ def record(sender, template, context):1038+ recorded.append((template, context))1039+1040+ with flask.template_rendered.temporarily_connected_to(record, app):1041+ rv = app.test_client().get('/')1042+ assert len(recorded) == 11043+ template, context = recorded[0]1044+ assert template.name == 'simple_template.html'1045+ assert context['whiskey'] == 421046+1047+ def test_request_signals(self):1048+ app = flask.Flask(__name__)1049+ calls = []1050+1051+ def before_request_signal(sender):1052+ calls.append('before-signal')1053+1054+ def after_request_signal(sender, response):1055+ assert response.data == 'stuff'1056+ calls.append('after-signal')1057+1058+ @app.before_request1059+ def before_request_handler():1060+ calls.append('before-handler')1061+1062+ @app.after_request1063+ def after_request_handler(response):1064+ calls.append('after-handler')1065+ response.data = 'stuff'1066+ return response1067+1068+ @app.route('/')1069+ def index():1070+ calls.append('handler')1071+ return 'ignored anyway'1072+1073+ flask.request_started.connect(before_request_signal, app)1074+ flask.request_finished.connect(after_request_signal, app)1075+1076+ try:1077+ rv = app.test_client().get('/')1078+ assert rv.data == 'stuff'1079+1080+ assert calls == ['before-signal', 'before-handler',1081+ 'handler', 'after-handler',1082+ 'after-signal']1083+ finally:1084+ flask.request_started.disconnect(before_request_signal, app)1085+ flask.request_finished.disconnect(after_request_signal, app)1086+1087+ def test_request_exception_signal(self):1088+ app = flask.Flask(__name__)1089+ recorded = []1090+1091+ @app.route('/')1092+ def index():1093+ 1/01094+1095+ def record(sender, exception):1096+ recorded.append(exception)1097+1098+ with flask.got_request_exception.temporarily_connected_to(record):1099+ assert app.test_client().get('/').status_code == 5001100+ assert len(recorded) == 11101+ assert isinstance(recorded[0], ZeroDivisionError)1102+1103+1104 def suite():1105 from minitwit_tests import MiniTwitTestCase1106 from flaskr_tests import FlaskrTestCase1107 suite = unittest.TestSuite()6 unmodified lines1114 suite.addTest(unittest.makeSuite(ConfigTestCase))1115 suite.addTest(unittest.makeSuite(SubdomainTestCase))1116 if flask.json_available:1117 suite.addTest(unittest.makeSuite(JSONTestCase))1118+ if flask.signals_available:1119+ suite.addTest(unittest.makeSuite(TestSignals))1120 suite.addTest(unittest.makeSuite(MiniTwitTestCase))1121 suite.addTest(unittest.makeSuite(FlaskrTestCase))1122 return suite1123 3 unmodified linesmodified:CHANGES+5 added
26 unmodified lines27 is now optional to be consistent with the function of the28 same name on the application object.29 - added a :func:`flask.make_response` function that simplifies30 creating response object instances in views.31+- added signalling support based on blinker. This feature is currently32+ optional and supposed to be used by extensions and applications. If33+ you want to use it, make sure to have `blinker`_ installed.34 35+.. _blinker: http://pypi.python.org/pypi/blinker36+37 Version 0.5.238 -------------39 40 Bugfix Release, released on July 15th 2010105 unmodified linesmodified:Makefile+4 added-1 removed
1-.PHONY: clean-pyc test upload-docs1+.PHONY: clean-pyc test upload-docs docs2 3 all: clean-pyc test4 5 test:13 unmodified lines19 cd docs/_build/; mv html flask-docs; zip -r flask-docs.zip flask-docs; mv flask-docs html20 scp -r docs/_build/dirhtml/* pocoo.org:/var/www/flask.pocoo.org/docs/21 scp -r docs/_build/latex/Flask.pdf pocoo.org:/var/www/flask.pocoo.org/docs/flask-docs.pdf22 scp -r docs/_build/flask-docs.zip pocoo.org:/var/www/flask.pocoo.org/docs/23+24+docs:25+ $(MAKE) -C docs html