base.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # -*- coding: utf-8 -*-
  2. """
  3. sleekxmpp.xmlstream.handler.base
  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. import weakref
  10. class BaseHandler(object):
  11. """
  12. Base class for stream handlers. Stream handlers are matched with
  13. incoming stanzas so that the stanza may be processed in some way.
  14. Stanzas may be matched with multiple handlers.
  15. Handler execution may take place in two phases: during the incoming
  16. stream processing, and in the main event loop. The :meth:`prerun()`
  17. method is executed in the first case, and :meth:`run()` is called
  18. during the second.
  19. :param string name: The name of the handler.
  20. :param matcher: A :class:`~sleekxmpp.xmlstream.matcher.base.MatcherBase`
  21. derived object that will be used to determine if a
  22. stanza should be accepted by this handler.
  23. :param stream: The :class:`~sleekxmpp.xmlstream.xmlstream.XMLStream`
  24. instance that the handle will respond to.
  25. """
  26. def __init__(self, name, matcher, stream=None):
  27. #: The name of the handler
  28. self.name = name
  29. #: The XML stream this handler is assigned to
  30. self.stream = None
  31. if stream is not None:
  32. self.stream = weakref.ref(stream)
  33. stream.register_handler(self)
  34. self._destroy = False
  35. self._payload = None
  36. self._matcher = matcher
  37. def match(self, xml):
  38. """Compare a stanza or XML object with the handler's matcher.
  39. :param xml: An XML or
  40. :class:`~sleekxmpp.xmlstream.stanzabase.ElementBase` object
  41. """
  42. return self._matcher.match(xml)
  43. def prerun(self, payload):
  44. """Prepare the handler for execution while the XML
  45. stream is being processed.
  46. :param payload: A :class:`~sleekxmpp.xmlstream.stanzabase.ElementBase`
  47. object.
  48. """
  49. self._payload = payload
  50. def run(self, payload):
  51. """Execute the handler after XML stream processing and during the
  52. main event loop.
  53. :param payload: A :class:`~sleekxmpp.xmlstream.stanzabase.ElementBase`
  54. object.
  55. """
  56. self._payload = payload
  57. def check_delete(self):
  58. """Check if the handler should be removed from the list
  59. of stream handlers.
  60. """
  61. return self._destroy
  62. # To comply with PEP8, method names now use underscores.
  63. # Deprecated method names are re-mapped for backwards compatibility.
  64. BaseHandler.checkDelete = BaseHandler.check_delete