/circuits/core/futures.py

https://bitbucket.org/prologic/circuits/ · Python · 51 lines · 32 code · 6 blank · 13 comment · 3 complexity · db9642478cbedc4fccb2c51784a45d48 MD5 · raw file

  1. # Module: future
  2. # Date: 6th February 2010
  3. # Author: James Mills, prologic at shortcircuit dot net dot au
  4. """Futures
  5. circuits supports the concept of "future" events. In circuits futures are
  6. event handlers that are specially designed to be run in the background
  7. either in a Thread or a Process. If you have event handlers that may
  8. potentially "block" then wrapping them by the @future decorator unblocks
  9. the bottle-neck caused by the "blocking" event handler(s).
  10. Support for using a Thread or Process pool is also supported by specifying
  11. an optional `pool` keyword argument and supplying an instance to a
  12. ``circuits.core.pool.Pool``.
  13. """
  14. from uuid import uuid4 as uuid
  15. from functools import update_wrapper
  16. from .values import Value
  17. from .utils import findcmp
  18. from .workers import Worker
  19. from .pools import Pool, Task
  20. def future(pool=None):
  21. """Decorator to wrap an event handler in a future Task
  22. This decorator wraps an event handler into a background Task
  23. executing the event handler function in the background.
  24. :param pool: An optional thread/process pool
  25. :type pool: Pool
  26. """
  27. def decorate(f):
  28. def wrapper(self, event, *args, **kwargs):
  29. event.future = True
  30. p = getattr(self, "_pool", pool)
  31. if p is None:
  32. p = findcmp(self.root, Pool)
  33. if p is not None:
  34. setattr(self, "_pool", p)
  35. return self.fire(Task(f, self, *args, **kwargs), target=p)
  36. else:
  37. return Worker(channel=str(uuid())).fire(
  38. Task(f, self, *args, **kwargs))
  39. wrapper.event = True
  40. return update_wrapper(wrapper, f)
  41. return decorate