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.

httpstreamformat.py 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # httpstreamformat.py
  2. # ~~~~~~~~~
  3. # This module implements the HttpStreamFormat class.
  4. # :authors: Justin Karneges, Konstantin Bokarius.
  5. # :copyright: (c) 2015 by Fanout, Inc.
  6. # :license: MIT, see LICENSE for more details.
  7. from base64 import b64encode
  8. from pubcontrol import Format
  9. from .gripcontrol import _bin_or_text
  10. # The HttpStreamFormat class is the format used to publish messages to
  11. # HTTP stream clients connected to a GRIP proxy.
  12. class HttpStreamFormat(Format):
  13. # Initialize with either the message content or a boolean indicating that
  14. # the streaming connection should be closed. If neither the content nor
  15. # the boolean flag is set then an error will be raised.
  16. def __init__(self, content=None, close=False, content_filters=None):
  17. self.content = content
  18. self.close = close
  19. self.content_filters = content_filters
  20. if not self.close and self.content is None:
  21. raise ValueError('content not set')
  22. # The name used when publishing this format.
  23. def name(self):
  24. return 'http-stream'
  25. # Exports the message in the required format depending on whether the
  26. # message content is binary or not, or whether the connection should
  27. # be closed.
  28. def export(self):
  29. out = dict()
  30. if self.close:
  31. out['action'] = 'close'
  32. else:
  33. if self.content_filters is not None:
  34. out['content-filters'] = self.content_filters
  35. is_text, val = _bin_or_text(self.content)
  36. if is_text:
  37. out['content'] = val
  38. else:
  39. out['content-bin'] = b64encode(val)
  40. return out