I use two streams: the first one listens to WebSocket, the second one runs only once, in order to subscribe the application to events after the WebSocket start.

import aiohttp import requests import json import threading ws_connected = False сlass ProcessEvent(object): # Some class def __init__(self): pass class WSListenerThread(threading.Thread): def run(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(listen()) async def listen(): async with aiohttp.ClientSession(auth=ARI_AUTH) as session: async with session.ws_connect('ws://localhost/events') as ws: ws_connected = True async for msg in ws: event = ProcessEvent(msg=msg.data) await event.check() class Subscriber(threading.Thread): def run(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self.resubscribe()) def resubscribe(): while not ws_connected: pass requests.post("http://localhost/something", data="payload=") if __name__ == '__main__': try: event_listener = WSListenerThread() event_listener.start() subscriber = Subscriber() subscriber.start() except KeyboardInterrupt: print("Pressing \"<CTRL> + <C>\".") # Как отправить сигнал на закрытие WS в потоке event_listener? sys.exit(0) 

How to close the stream from the outside?

  • one
    What is the meaning of the two cycles of events to start? Asyncio related question : not stopping your coroutines correctly - jfs
  • I work with Asterisk REST. DELETE / POST / PUT-requests must be sent after connecting to the socket, depending on the server status and only once. In a hurry - I could not think of a way to do it differently. Therefore, in one - I listen to the socket and process its events, in the second I subscribe to the necessary dependencies. - Tihon
  • I will try to implement as a related issue. - Tihon

0