signals.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import typing as t
  2. try:
  3. from blinker import Namespace
  4. signals_available = True
  5. except ImportError:
  6. signals_available = False
  7. class Namespace: # type: ignore
  8. def signal(self, name: str, doc: t.Optional[str] = None) -> "_FakeSignal":
  9. return _FakeSignal(name, doc)
  10. class _FakeSignal:
  11. """If blinker is unavailable, create a fake class with the same
  12. interface that allows sending of signals but will fail with an
  13. error on anything else. Instead of doing anything on send, it
  14. will just ignore the arguments and do nothing instead.
  15. """
  16. def __init__(self, name: str, doc: t.Optional[str] = None) -> None:
  17. self.name = name
  18. self.__doc__ = doc
  19. def send(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
  20. pass
  21. def _fail(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
  22. raise RuntimeError(
  23. "Signalling support is unavailable because the blinker"
  24. " library is not installed."
  25. ) from None
  26. connect = connect_via = connected_to = temporarily_connected_to = _fail
  27. disconnect = _fail
  28. has_receivers_for = receivers_for = _fail
  29. del _fail
  30. # The namespace for code signals. If you are not Flask code, do
  31. # not put signals in here. Create your own namespace instead.
  32. _signals = Namespace()
  33. # Core signals. For usage examples grep the source code or consult
  34. # the API documentation in docs/api.rst as well as docs/signals.rst
  35. template_rendered = _signals.signal("template-rendered")
  36. before_render_template = _signals.signal("before-render-template")
  37. request_started = _signals.signal("request-started")
  38. request_finished = _signals.signal("request-finished")
  39. request_tearing_down = _signals.signal("request-tearing-down")
  40. got_request_exception = _signals.signal("got-request-exception")
  41. appcontext_tearing_down = _signals.signal("appcontext-tearing-down")
  42. appcontext_pushed = _signals.signal("appcontext-pushed")
  43. appcontext_popped = _signals.signal("appcontext-popped")
  44. message_flashed = _signals.signal("message-flashed")