signals.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.signals
  4. ~~~~~~~~~~~~~
  5. Implements signals based on blinker if available, otherwise
  6. falls silently back to a noop.
  7. :copyright: © 2010 by the Pallets team.
  8. :license: BSD, see LICENSE for more details.
  9. """
  10. signals_available = False
  11. try:
  12. from blinker import Namespace
  13. signals_available = True
  14. except ImportError:
  15. class Namespace(object):
  16. def signal(self, name, doc=None):
  17. return _FakeSignal(name, doc)
  18. class _FakeSignal(object):
  19. """If blinker is unavailable, create a fake class with the same
  20. interface that allows sending of signals but will fail with an
  21. error on anything else. Instead of doing anything on send, it
  22. will just ignore the arguments and do nothing instead.
  23. """
  24. def __init__(self, name, doc=None):
  25. self.name = name
  26. self.__doc__ = doc
  27. def _fail(self, *args, **kwargs):
  28. raise RuntimeError('signalling support is unavailable '
  29. 'because the blinker library is '
  30. 'not installed.')
  31. send = lambda *a, **kw: None
  32. connect = disconnect = has_receivers_for = receivers_for = \
  33. temporarily_connected_to = connected_to = _fail
  34. del _fail
  35. # The namespace for code signals. If you are not Flask code, do
  36. # not put signals in here. Create your own namespace instead.
  37. _signals = Namespace()
  38. # Core signals. For usage examples grep the source code or consult
  39. # the API documentation in docs/api.rst as well as docs/signals.rst
  40. template_rendered = _signals.signal('template-rendered')
  41. before_render_template = _signals.signal('before-render-template')
  42. request_started = _signals.signal('request-started')
  43. request_finished = _signals.signal('request-finished')
  44. request_tearing_down = _signals.signal('request-tearing-down')
  45. got_request_exception = _signals.signal('got-request-exception')
  46. appcontext_tearing_down = _signals.signal('appcontext-tearing-down')
  47. appcontext_pushed = _signals.signal('appcontext-pushed')
  48. appcontext_popped = _signals.signal('appcontext-popped')
  49. message_flashed = _signals.signal('message-flashed')