0

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())

1 Answer 1

1

Asyncio is the right tool for this job, you don't need threads, but you do need to switch from requests to an asyncio-compatible http library, such as aiohttp.

Do i need "result = await on_message(msg)" or "result = on_message(msg)" in the ws_connect function?

Since on_message is async def, you need either await or asyncio.create_task(). If you need to wait for the result, you await. Otherwise, you call asyncio.create_task(on_message(msg)) and let it run in the background.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.