Skip to content
Myr

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

10 files+212 added−4 removed

modified:docs/api.rst+51 added
349 unmodified lines
350 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.354355Signals356-------357358.. versionadded:: 0.6359360.. data:: signals_available361362 `True` if the signalling system is available. This is the case363 when `blinker`_ is installed.364365.. data:: template_rendered366367 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`).370371.. data:: request_started372373 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`.377378.. data:: request_finished379380 This signal is sent right before the response is sent to the client.381 It is passed the response to be sent named `response`.382383.. data:: got_request_exception384385 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`.389390.. class:: flask.signals.Namespace391392 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.396397 .. method:: signal(name, doc=None)398399 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.403404.. _blinker: http://pypi.python.org/pypi/blinker
modified:docs/conf.py+2 added-1 removed
243 unmodified lines
244intersphinx_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}251252pygments_style = 'flask_theme_support.FlaskyStyle'
modified:flask/__init__.py+4 added
22 unmodified lines
23from .globals import current_app, g, request, session, _request_ctx_stack24from .module import Module25from .templating import render_template, render_template_string2627# the signals28from .signals import signals_available, template_rendered, request_started, \29 request_finished, got_request_exception3031# only import json if it's available32if json_available:33 from .helpers import json
modified:flask/app.py+4 added
30 unmodified lines
31from .session import Session, _NullSession32from .module import _ModuleSetupState33from .templating import _DispatchingJinjaLoader, \34 _default_template_ctx_processor35from .signals import request_started, request_finished, got_request_exception3637# a lock used for logger initialization38_logger_lock = Lock()39
617 unmodified lines
657 exists, a default 500 internal server error message is displayed.658659 .. 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 lines
792 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 lines
803 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)809810 def request_context(self, environ):811 """Creates a request context from the given environment and binds
48 unmodified lines
added:flask/signals.py+50 added
1# -*- coding: utf-8 -*-2"""3 flask.signals4 ~~~~~~~~~~~~~56 Implements signals based on blinker if available, otherwise7 falls silently back to a noop89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12signals_available = False13try:14 from blinker import Namespace15 signals_available = True16 _signals = Namespace()17except 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 """2728 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 _fail3940# 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()434445# core signals. For usage examples grep the sourcecode or consult46# the API documentation in docs/api.rst as well as docs/signals.rst47template_rendered = _signals.signal('template-rendered')48request_started = _signals.signal('request-started')49request_finished = _signals.signal('request-finished')50got_request_exception = _signals.signal('got-request-exception')
modified:flask/templating.py+12 added-2 removed
9 unmodified lines
10"""11from jinja2 import BaseLoader, FileSystemLoader, TemplateNotFound1213from .globals import _request_ctx_stack14from .signals import template_rendered151617def _default_template_ctx_processor():18 """Default template context processor. Injects `request`,
40 unmodified lines
59 result.append('%s/%s' % (name, template))60 return result616263def _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 rv686970def render_template(template_name, **context):71 """Renders a template from the template folder with the given72 context.73
2 unmodified lines
76 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)828384def render_template_string(source, **context):85 """Renders a template from the given template source string
5 unmodified lines
91 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
modified:tests/flask_tests.py+79 added
1022 unmodified lines
1023 rv = c.get('/', 'http://mitsuhiko.localhost/')1024 assert rv.data == 'index for mitsuhiko'102510261027class TestSignals(unittest.TestCase):10281029 def test_template_rendered(self):1030 app = flask.Flask(__name__)10311032 @app.route('/')1033 def index():1034 return flask.render_template('simple_template.html', whiskey=42)10351036 recorded = []1037 def record(sender, template, context):1038 recorded.append((template, context))10391040 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'] == 4210461047 def test_request_signals(self):1048 app = flask.Flask(__name__)1049 calls = []10501051 def before_request_signal(sender):1052 calls.append('before-signal')10531054 def after_request_signal(sender, response):1055 assert response.data == 'stuff'1056 calls.append('after-signal')10571058 @app.before_request1059 def before_request_handler():1060 calls.append('before-handler')10611062 @app.after_request1063 def after_request_handler(response):1064 calls.append('after-handler')1065 response.data = 'stuff'1066 return response10671068 @app.route('/')1069 def index():1070 calls.append('handler')1071 return 'ignored anyway'10721073 flask.request_started.connect(before_request_signal, app)1074 flask.request_finished.connect(after_request_signal, app)10751076 try:1077 rv = app.test_client().get('/')1078 assert rv.data == 'stuff'10791080 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)10861087 def test_request_exception_signal(self):1088 app = flask.Flask(__name__)1089 recorded = []10901091 @app.route('/')1092 def index():1093 1/010941095 def record(sender, exception):1096 recorded.append(exception)10971098 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)110211031104def suite():1105 from minitwit_tests import MiniTwitTestCase1106 from flaskr_tests import FlaskrTestCase1107 suite = unittest.TestSuite()
6 unmodified lines
1114 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 lines
modified:CHANGES+5 added
26 unmodified lines
27 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.3435.. _blinker: http://pypi.python.org/pypi/blinker3637Version 0.5.238-------------3940Bugfix Release, released on July 15th 2010
105 unmodified lines
modified:Makefile+4 added-1 removed
1.PHONY: clean-pyc test upload-docs1.PHONY: clean-pyc test upload-docs docs23all: clean-pyc test45test:
13 unmodified lines
19 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/2324docs:25 $(MAKE) -C docs html