signals.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 Pallets
  8. :license: BSD-3-Clause
  9. """
  10. try:
  11. from blinker import Namespace
  12. signals_available = True
  13. except ImportError:
  14. signals_available = False
  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 send(self, *args, **kwargs):
  28. pass
  29. def _fail(self, *args, **kwargs):
  30. raise RuntimeError(
  31. "Signalling support is unavailable because the blinker"
  32. " library is not installed."
  33. )
  34. connect = connect_via = connected_to = temporarily_connected_to = _fail
  35. disconnect = _fail
  36. has_receivers_for = receivers_for = _fail
  37. del _fail
  38. # The namespace for code signals. If you are not Flask code, do
  39. # not put signals in here. Create your own namespace instead.
  40. _signals = Namespace()
  41. # Core signals. For usage examples grep the source code or consult
  42. # the API documentation in docs/api.rst as well as docs/signals.rst
  43. template_rendered = _signals.signal("template-rendered")
  44. before_render_template = _signals.signal("before-render-template")
  45. request_started = _signals.signal("request-started")
  46. request_finished = _signals.signal("request-finished")
  47. request_tearing_down = _signals.signal("request-tearing-down")
  48. got_request_exception = _signals.signal("got-request-exception")
  49. appcontext_tearing_down = _signals.signal("appcontext-tearing-down")
  50. appcontext_pushed = _signals.signal("appcontext-pushed")
  51. appcontext_popped = _signals.signal("appcontext-popped")
  52. message_flashed = _signals.signal("message-flashed")