Create SseStream
This commit is contained in:
parent
92f2a2c8f4
commit
a6dfc299b8
|
|
@ -0,0 +1,72 @@
|
|||
import queue
|
||||
import sse
|
||||
from exceptions import TooManyConnections
|
||||
|
||||
class SseStream():
|
||||
__queues = {}
|
||||
__maxConnections = 10
|
||||
__queue_size = 50
|
||||
|
||||
@staticmethod
|
||||
def setMaxConnections(maxConnections = 10):
|
||||
""" Set maximum number of concurrent connections
|
||||
---
|
||||
Paremeters:
|
||||
------
|
||||
maxConnections: int, optional
|
||||
The number of maximum concurrent connections ( default value is 10) """
|
||||
SseStream.__maxConnections = maxConnections
|
||||
|
||||
@staticmethod
|
||||
def setQueueSize(queueSize = 50):
|
||||
""" Set the queue size for stored messages
|
||||
---
|
||||
Parementers
|
||||
------
|
||||
queueSize: int, optional
|
||||
The number of stored messages in the queue, set to <=0 for unlimited size ( default value is 50 ) """
|
||||
SseStream.__queue_size = queueSize
|
||||
|
||||
def __init__(self, id):
|
||||
""" Init a new stream
|
||||
---
|
||||
Paremeters:
|
||||
------
|
||||
id: string
|
||||
The unique id of the client
|
||||
"""
|
||||
if len( self.__queues ) >= self.__maxConnections:
|
||||
raise TooManyConnections
|
||||
|
||||
if not self.__queues.get( id ):
|
||||
self._queue = queue.Queue( self.__queue_size )
|
||||
self.__queues[ id ] = self._queue
|
||||
|
||||
print(f"Queue size: {self.__queue_size}; Connections: { len( self.__queues ) }/{self.__maxConnections}; ID: {id}")
|
||||
|
||||
def __del__(self):
|
||||
""" Deregister client from queue - clean up """
|
||||
print( "Stream object is deleted")
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
""" Method which is called regular to send out the event """
|
||||
while True:
|
||||
msg = self.queue.get(block=True, timeout=None)
|
||||
if isinstance( msg, sse ):
|
||||
for data in msg:
|
||||
yield data
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
SseStream.setMaxConnections(5)
|
||||
SseStream.setQueueSize(10)
|
||||
sse = SseStream("Test")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in New Issue