2021-05-08 14:39:00 +00:00
|
|
|
import json
|
|
|
|
import sseclient
|
|
|
|
from ._transport import Transport
|
|
|
|
|
|
|
|
|
|
|
|
class ServerSentEventsTransport(Transport):
|
|
|
|
def __init__(self, session, connection):
|
|
|
|
Transport.__init__(self, session, connection)
|
|
|
|
self.__response = None
|
|
|
|
|
|
|
|
def _get_name(self):
|
|
|
|
return 'serverSentEvents'
|
|
|
|
|
|
|
|
def start(self):
|
2021-10-21 00:46:22 +00:00
|
|
|
connect_url = self._get_url('connect')
|
|
|
|
self.__response = iter(sseclient.SSEClient(connect_url, session=self._session))
|
2021-05-08 14:39:00 +00:00
|
|
|
self._session.get(self._get_url('start'))
|
|
|
|
|
|
|
|
def _receive():
|
2021-10-21 00:46:22 +00:00
|
|
|
try:
|
|
|
|
notification = next(self.__response)
|
|
|
|
except StopIteration:
|
|
|
|
return
|
|
|
|
else:
|
2021-05-15 13:41:39 +00:00
|
|
|
if notification.data != 'initialized':
|
|
|
|
self._handle_notification(notification.data)
|
2021-05-08 14:39:00 +00:00
|
|
|
|
|
|
|
return _receive
|
|
|
|
|
|
|
|
def send(self, data):
|
|
|
|
response = self._session.post(self._get_url('send'), data={'data': json.dumps(data)})
|
|
|
|
parsed = json.loads(response.content)
|
|
|
|
self._connection.received.fire(**parsed)
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
self._session.get(self._get_url('abort'))
|