Program listens to a websocket. When a certain message is received, we need to wait 5 seconds then run a restapi call out to another server.
It works with a single websocket message that I am able to manually trigger. However, there will be a high volume of websocket messages that I will be processing around ~50-100 messages per second. Not sure If I am going about the right method or not. I hope asyncio is the right tool for the job too or if I should do something with threads.
Also, Do i need "result = await on_message(msg)" or "result = on_message(msg)" in the ws_connect function? I am completely new to asyncio
Thanks in advance....
async def do_long_process(id):
# Need to wait 5 seconds before doing anything
await asyncio.sleep(5)
return requests.post('http://do.action.com/%s', id)
async def on_message(message):
msg = json.loads(message)
if msg['type'] == 'takeaction':
response = await do_long_process(msg['id'])
async def ws_connect():
uri = f'ws://server/ws'
async with websockets.connect(uri) as ws:
while True:
msg = await ws.recv()
result = await on_message(msg)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(ws_connect())