Exemple #1
0
async def test_custom_response_cls(with_subclass):
    class CustomResponse(EventSourceResponse if with_subclass else object):
        pass

    request = make_mocked_request('GET', '/')
    if with_subclass:
        with pytest.warns(RuntimeWarning):
            sse_response(request, response_cls=CustomResponse)
    else:
        with pytest.raises(TypeError):
            sse_response(request, response_cls=CustomResponse)
async def subscribe(request):

    print('new sub created!')

    data_dir = os.environ.get('DATA_DIR', '/data/')
    data_file = os.environ.get('FILE_ALL', 'all_data.csv')
    data_loc = os.path.join(data_dir, data_file)

    if not os.path.isfile(data_loc):
        join_data_preprocessing()

    # instantiate generator
    r = row_generator(data_loc)

    print('\n REQUEST MADE WAS: ', request)

    async with sse_response(request) as resp:

        while True:
            try:
                await asyncio.sleep(1)
                await resp.send(next(r))
            except StopIteration:  #catches end of generator
                break
        return resp
Exemple #3
0
async def sse_client(request):
    async with aiohttp_sse.sse_response(request) as response:
        response: aiohttp_sse.EventSourceResponse

        app = request.app
        queue = asyncio.Queue()

        logger.info("client connected")

        async with app["api_server"].cache_lock:
            app["api_server"].channels.add(queue)

            for k, v in app["api_server"].cache.items():
                await queue.put((k, v))

        try:
            while not response.task.done():
                (type_, payload) = await queue.get()
                await response.send(payload, event=type_)
                queue.task_done()
        finally:
            app["api_server"].channels.remove(queue)
            logger.info("client disconnected")

    return response
Exemple #4
0
async def hello(request):
    async with sse_response(request) as resp:
        for i in range(0, 100):
            print('foo')
            await asyncio.sleep(1)
            await resp.send('foo {}'.format(i))
    return resp
Exemple #5
0
async def sse_data_handler(request):
    async with sse_response(request) as resp:
        while True:
            data = 'Server Time : {}'.format(datetime.now())
            await resp.send(data)
            await asyncio.sleep(1, loop=request.app.loop)
    return resp
Exemple #6
0
async def chat(request):
    async with sse_response(request) as response:
        app = request.app
        print('Someone joined.')

        this_queue = asyncio.Queue()
        app['channels'].add(this_queue)
        for queue in app['channels']:
            await queue.put(json.dumps(dict(online=len(app['channels']))))

        try:
            for message in app['last_messages']:
                logging.warning(f"last_message: message: {message}")
                await response.send(message)

            while not response.task.done():
                payload = await this_queue.get()
                await response.send(payload)
                this_queue.task_done()
        finally:
            print(f"someone left, online{len(app['channels'])}")

            for queue in app['channels']:
                await queue.put(
                    json.dumps(dict(online=len(app['channels']) - 1)))
            app['channels'].remove(this_queue)

    return response
async def sse_connect(request):
    client_name = request.match_info.get("client_name")

    bot = request.app["bot"]

    try:
        events_queue: asyncio.Queue = await bot.actuators.turn_on_actuator(
            client_name)
    except exceptions.ActuatorAlreadyConnected:
        raise HTTPTooManyRequests()

    log.info(f"{request.remote} has been joined to terminal: {client_name}")
    headers = {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": "true",
    }

    async with sse_response(request, headers=headers) as response:
        try:
            intro_event = get_intro_event(client_name)
            await response.send(intro_event.data, event=intro_event.event)

            while not response.task.done():
                event = await events_queue.get()
                log.info(f"{request.remote} sent message with {event}")
                await response.send(event.data, event=event.event)
                events_queue.task_done()
        finally:
            await bot.actuators.turn_off_actuator(client_name)
            log.info(
                f"{request._transport_peername[0]} has been left from terminal: {client_name}"
            )
    return response
Exemple #8
0
 async def open_feed(self, request: web.Request):
     async with self.feed.open_session() as queue:
         async with sse_response(request) as resp:
             resp.ping_interval = self.ping_interval
             while True:
                 msg = await queue.get()
                 await resp.send(msg.decode())
async def get_call_info_notifications(request: web.Request):
    manager = request.app['monitoring']

    async with sse_response(request) as resp:
        with manager.calls_receiver() as receiver:
            async for data in receiver():
                await resp.send(json.dumps(data))
    return resp
Exemple #10
0
async def events(request):
    try:
        async with sse_response(request) as resp:
            async for event in events_generator.generator():
                await resp.send(to_json(event))
        return resp
    except BaseException:
        logger.exception('get /events failed')
Exemple #11
0
async def feed(request):
    queue = asyncio.Queue()
    connections.add(queue)
    with suppress(asyncio.CancelledError):
        async with sse_response(request) as resp:
            while data := await queue.get():
                print('sending data:', data)
                await resp.send(json.dumps(data))
Exemple #12
0
async def stream(request):
    async with sse_response(request) as resp:
        await resp.send(imageUri(recv.lastFrame[0]))
        await resp.send(json.dumps(recv.lastFrame[1]))
        async for frame, msg in recv.frames():
            await resp.send(json.dumps(msg))
            await resp.send(imageUri(frame))
    return resp
async def event_handler(request):
    loop = request.app.loop
    async with sse_response(request) as resp:
        while True:
            data = 'Server Time : {}'.format(datetime.now())
            print(data)
            await resp.send(data)
            await asyncio.sleep(1, loop=loop)
Exemple #14
0
 async def func(request):
     h = {'X-SSE': 'aiohttp_sse'}
     async with sse_response(request, headers=h) as sse:
         sse.send('foo')
         sse.send('foo', event='bar')
         sse.send('foo', event='bar', id='xyz')
         sse.send('foo', event='bar', id='xyz', retry=1)
     return sse
Exemple #15
0
 async def func(request):
     h = {'X-SSE': 'aiohttp_sse'}
     lines = line_sep.join(['foo', 'bar', 'xyz'])
     async with sse_response(request, headers=h, sep=stream_sep) as sse:
         await sse.send(lines)
         await sse.send(lines, event='bar')
         await sse.send(lines, event='bar', id='xyz')
         await sse.send(lines, event='bar', id='xyz', retry=1)
     return sse
Exemple #16
0
 async def get_system_info(self, request):
     loop = request.app.loop
     async with sse_response(request, headers=self.cors_headers) as resp:
         while True:
             await resp.send(ujson.dumps({"data":
                                          self.__get_system_info()}),
                             event="systemInfo")
             await asyncio.sleep(3, loop=loop)
     return resp
Exemple #17
0
async def subscribe_status(request):
    async with sse_response(request) as resp:
        async for line in request.app['automaton_runner']['runner'].log_source:
            await resp.send(
                json.dumps({
                    'message':
                    line,
                    'running':
                    request.app['automaton_runner']['runner'].is_running
                }))
Exemple #18
0
async def chatMsg(request):
    loop = request.app.loop
    async with sse_response(request) as resp:
        while True:
            if len(chat_msgs) > 0:
                await resp.send(json.dumps(chat_msgs[0]))
                chat_msgs.pop(0)

            await asyncio.sleep(1, loop=loop)
    return resp
Exemple #19
0
async def get_install_stream(request):
    print('Install stream requested')
    async with sse_response(request) as resp:
        await send_json_sse(resp, INSTALL_STATE)
        last_update_time = INSTALL_STATE['update_time']
        while True:
            await asyncio.sleep(0.2)
            if last_update_time < INSTALL_STATE['update_time']:
                await send_json_sse(resp, INSTALL_STATE)
                last_update_time = INSTALL_STATE['update_time']
    async def handle_sse(self, request):
        if self._sse_lock:
            raise Exception('Only one open stream is currently supported.')
        try:
            self._sse_lock = True
            # This sets up the eventSource stream
            async with sse_response(request) as resp:
                # Setup variables
                start_time = datetime.now()
                last_message_body = {}

                print(
                    f"{TColors.RED}Started playback due to SSE connection{TColors.END}"
                )

                # While we still have messages left to show...
                while not self.messages.is_empty():
                    # Are we past the timestamp of the next message?
                    now = datetime.now()
                    time_since_start = now - start_time
                    seconds = time_since_start.total_seconds() * self.speed

                    if seconds >= self.messages.top()[0]:
                        # We are? Then send a new event
                        print(
                            f"{TColors.GREEN}SSE: {TColors.BLUE2}{self.messages.top()[0]:7.2f}/{self.messages.bottom()[0]:7.2f}{TColors.END}\r"
                        )
                        message = self.messages.top()[1]

                        if isinstance(message, int):
                            # If it's just an int, that means we have identical content to the previous message
                            # Was used when the stream included lastUpdateTime to indicate we got a message with a new lastUpdateTime that was identical
                            message = last_message_body
                            message["value"][
                                "lastUpdateTime"] = self.messages.top()[1]
                        else:
                            last_message_body = message

                        # Actually send the event
                        await resp.send(json.dumps(message))

                        # Advance
                        self.messages.pop()
                    else:
                        # If we're not to the next message's timestamp yet, sleep for a bit
                        await asyncio.sleep(0.05)

                # We've hit the end of the stream
                print(f"{TColors.RED}Finished SSE playback{TColors.END}")

            # Close connection
            return resp
        finally:
            self._sse_lock = False
Exemple #21
0
async def hello(request):
    async with sse_response(request) as resp:
        await update_sse_with_tick(resp, managed_tick_value)
        last_value = managed_tick_value.value
        while True:
            await asyncio.sleep(1)
            if managed_tick_value.value != last_value:
                await update_sse_with_tick(resp, managed_tick_value)
                last_value = managed_tick_value.value

        managed_sse_list.append(resp)
Exemple #22
0
async def events(request):
    loop = request.app.loop
    async with sse_response(request) as resp:
        while True:
            try:
                data = queue.get(block=False)
                logging.warning(f"transmitting item from queue: {data}")
                await resp.send(data)
            except:
                pass
            await asyncio.sleep(0.001, loop=loop)
    return resp
Exemple #23
0
async def subscribe_games(request):
    async with sse_response(request) as response:
        app = request.app
        queue = asyncio.Queue()
        app['channels'].add(queue)
        try:
            while not response.task.done():
                payload = await queue.get()
                await response.send(payload)
                queue.task_done()
        finally:
            app['channels'].remove(queue)
    return response
Exemple #24
0
 def func(request):
     if with_sse_response:
         resp = yield from sse_response(request,
                                        headers={'X-SSE': 'aiohttp_sse'})
     else:
         resp = EventSourceResponse(headers={'X-SSE': 'aiohttp_sse'})
         yield from resp.prepare(request)
     resp.send('foo')
     resp.send('foo', event='bar')
     resp.send('foo', event='bar', id='xyz')
     resp.send('foo', event='bar', id='xyz', retry=1)
     resp.stop_streaming()
     yield from resp.wait()
     return resp
Exemple #25
0
async def vedio_thread1(request):
    print('send')
    async with sse_response(request) as resp:
        while True:
            # if len(server.clients) > 0:
            image = cv2.imencode('.jpg', frame)[1]
            base64_data = base64.b64encode(image)
            steam = base64_data.decode()
            await resp.send(steam)
            await asyncio.sleep(0.02)
            # print('data:image/jpeg;base64,%s'%s)
            # server.send_message_to_all('data:image/jpeg;base64,' + s)
            # time.sleep(0.01)
    return resp
Exemple #26
0
 async def notifyChange(self, request):
     async with sse_response(request) as response:
         events = asyncio.Queue()
         self.queue.addListener(events)
         response.content_type = "application/json"
         try:
             payload = await events.get()
             while not response.task.done() and payload:
                 body = json.dumps(payload, cls=TrackEncoder)
                 await response.send(body)
                 events.task_done()
                 payload = await events.get()
         finally:
             self.queue.removeListener(events)
     return response
Exemple #27
0
async def subscribe_invites(request):
    async with sse_response(request) as response:
        app = request.app
        queue = asyncio.Queue()
        app['invite_channels'].add(queue)
        try:
            while not response.task.done():
                payload = await queue.get()
                await response.send(payload)
                queue.task_done()
        except ConnectionResetError:
            pass
        finally:
            app['invite_channels'].remove(queue)
    return response
Exemple #28
0
 async def get(self):
     ws = web.WebSocketResponse()
     if ws.can_prepare(self.request):
         await ws.prepare(self.request)
         async for led in self:
             await ws.send_json(led)
         return ws
     else:
         if self.request.headers.get('Accept') == 'text/event-stream':
             async with sse_response(self.request) as resp:
                 async for led in self:
                     resp.send(dumps(led))
             return resp
         else:
             async for led in self:
                 return json_response(led)
Exemple #29
0
async def messages(request):
    board = request.match_info['board']
    cursor = chat_dbs.find({
        'chat': board,
        'deleted': False
    },
                           cursor_type=pymongo.CursorType.TAILABLE)
    async with sse_response(request) as res:
        while True:
            if not cursor.alive:
                await asyncio.sleep(0.1)
                cursor = chat_dbs.find({'chat': board},
                                       cursor_type=pymongo.CursorType.TAILABLE,
                                       await_data=True)
                async for message in cursor:
                    data = serializer.dump(message)
                    res.send(data, event='chat')
        return res
Exemple #30
0
async def subscribe_notify(request):
    async with sse_response(request) as response:
        session = await aiohttp_session.get_session(request)
        session_user = session.get("user_name")

        user = request.app["users"].get(session_user)
        if user is None:
            return response

        user.notify_queue = asyncio.Queue()
        try:
            while not response.task.done():
                payload = await user.notify_queue.get()
                await response.send(payload)
                user.notify_queue.task_done()
        finally:
            user.notify_queue = None
    return response
Exemple #31
0
async def sse_handler(request):
    try:
        token = request.query['token']
    except KeyError:
        return web.HTTPBadRequest()

    loop = request.app.loop
    try:
        c_queue = _c_queue_mapping[token]
    except KeyError:
        c_queue = asyncio.Queue()
        _c_queue_mapping[token] = c_queue

    async with sse_response(request) as resp:
        while not _shutdown_event.is_set():
            try:
                msg = c_queue.get_nowait()
            except asyncio.QueueEmpty:
                await asyncio.sleep(0.2)
            else:
                await resp.send(msg)

    return resp