You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.4 KiB

4 years ago
  1. from __future__ import absolute_import
  2. from pydispatch import dispatcher
  3. from scrapy.utils import signal as _signal
  4. class SignalManager(object):
  5. def __init__(self, sender=dispatcher.Anonymous):
  6. self.sender = sender
  7. def connect(self, receiver, signal, **kwargs):
  8. """
  9. Connect a receiver function to a signal.
  10. The signal can be any object, although Scrapy comes with some
  11. predefined signals that are documented in the :ref:`topics-signals`
  12. section.
  13. :param receiver: the function to be connected
  14. :type receiver: callable
  15. :param signal: the signal to connect to
  16. :type signal: object
  17. """
  18. kwargs.setdefault('sender', self.sender)
  19. return dispatcher.connect(receiver, signal, **kwargs)
  20. def disconnect(self, receiver, signal, **kwargs):
  21. """
  22. Disconnect a receiver function from a signal. This has the
  23. opposite effect of the :meth:`connect` method, and the arguments
  24. are the same.
  25. """
  26. kwargs.setdefault('sender', self.sender)
  27. return dispatcher.disconnect(receiver, signal, **kwargs)
  28. def send_catch_log(self, signal, **kwargs):
  29. """
  30. Send a signal, catch exceptions and log them.
  31. The keyword arguments are passed to the signal handlers (connected
  32. through the :meth:`connect` method).
  33. """
  34. kwargs.setdefault('sender', self.sender)
  35. return _signal.send_catch_log(signal, **kwargs)
  36. def send_catch_log_deferred(self, signal, **kwargs):
  37. """
  38. Like :meth:`send_catch_log` but supports returning `deferreds`_ from
  39. signal handlers.
  40. Returns a Deferred that gets fired once all signal handlers
  41. deferreds were fired. Send a signal, catch exceptions and log them.
  42. The keyword arguments are passed to the signal handlers (connected
  43. through the :meth:`connect` method).
  44. .. _deferreds: https://twistedmatrix.com/documents/current/core/howto/defer.html
  45. """
  46. kwargs.setdefault('sender', self.sender)
  47. return _signal.send_catch_log_deferred(signal, **kwargs)
  48. def disconnect_all(self, signal, **kwargs):
  49. """
  50. Disconnect all receivers from the given signal.
  51. :param signal: the signal to disconnect from
  52. :type signal: object
  53. """
  54. kwargs.setdefault('sender', self.sender)
  55. return _signal.disconnect_all(signal, **kwargs)