Issue
I'm trying to create a Python script that will receive messages from a websocket connection and every time it receives a new message, it needs to run an asyncio task in the background.
In order to "simulate" this process, i made a blocking functio that starts counting with a while True
statement. The expected output is that every time a new message is received from the ws connection, a new count starts, but in my case, as soon as i run the script, the count function will block the whole code. How can i solve this?
Here is what i tried:
import asyncio
import websockets
import json
import time
#this is the blocking function..
def counter():
count = 0
while True:
print(count)
count += 1
time.sleep(0.5)
async def main():
while True:
try:
async with websockets.connect('MY-URL') as websocket:
while True:
msg = await asyncio.wait_for(websocket.recv(), 500)
try:
data = json.loads(msg)
await loop.create_task(counter())
except Exception as e:
print(e)
except Exception as e:
print(e)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Solution
You have two major problems here. Your first problem is, that you create an infinite loop in counter
and than call it, when you try to pass it to create_task
. This way create_task
is never even called.
The second obvious problem is, that you try to pass a method to create_task
while it expects a coroutine.
Define your counter
method again as coroutine using async def
and replace time.sleep
with asyncio.sleep
and I think it might work.
As a general note: You cannot have blocking code in the same thread as your event loop. This means never ever use time.sleep
in asynchronous code...
Answered By - thisisalsomypassword
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.