callback.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # -*- coding: utf-8 -*-
  2. """
  3. sleekxmpp.xmlstream.handler.callback
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Part of SleekXMPP: The Sleek XMPP Library
  6. :copyright: (c) 2011 Nathanael C. Fritz
  7. :license: MIT, see LICENSE for more details
  8. """
  9. from sleekxmpp.xmlstream.handler.base import BaseHandler
  10. class Callback(BaseHandler):
  11. """
  12. The Callback handler will execute a callback function with
  13. matched stanzas.
  14. The handler may execute the callback either during stream
  15. processing or during the main event loop.
  16. Callback functions are all executed in the same thread, so be aware if
  17. you are executing functions that will block for extended periods of
  18. time. Typically, you should signal your own events using the SleekXMPP
  19. object's :meth:`~sleekxmpp.xmlstream.xmlstream.XMLStream.event()`
  20. method to pass the stanza off to a threaded event handler for further
  21. processing.
  22. :param string name: The name of the handler.
  23. :param matcher: A :class:`~sleekxmpp.xmlstream.matcher.base.MatcherBase`
  24. derived object for matching stanza objects.
  25. :param pointer: The function to execute during callback.
  26. :param bool thread: **DEPRECATED.** Remains only for
  27. backwards compatibility.
  28. :param bool once: Indicates if the handler should be used only
  29. once. Defaults to False.
  30. :param bool instream: Indicates if the callback should be executed
  31. during stream processing instead of in the
  32. main event loop.
  33. :param stream: The :class:`~sleekxmpp.xmlstream.xmlstream.XMLStream`
  34. instance this handler should monitor.
  35. """
  36. def __init__(self, name, matcher, pointer, thread=False,
  37. once=False, instream=False, stream=None):
  38. BaseHandler.__init__(self, name, matcher, stream)
  39. self._pointer = pointer
  40. self._once = once
  41. self._instream = instream
  42. def prerun(self, payload):
  43. """Execute the callback during stream processing, if
  44. the callback was created with ``instream=True``.
  45. :param payload: The matched
  46. :class:`~sleekxmpp.xmlstream.stanzabase.ElementBase` object.
  47. """
  48. if self._once:
  49. self._destroy = True
  50. if self._instream:
  51. self.run(payload, True)
  52. def run(self, payload, instream=False):
  53. """Execute the callback function with the matched stanza payload.
  54. :param payload: The matched
  55. :class:`~sleekxmpp.xmlstream.stanzabase.ElementBase` object.
  56. :param bool instream: Force the handler to execute during stream
  57. processing. This should only be used by
  58. :meth:`prerun()`. Defaults to ``False``.
  59. """
  60. if not self._instream or instream:
  61. self._pointer(payload)
  62. if self._once:
  63. self._destroy = True
  64. del self._pointer