Reputation: 111
I am making a small webpage which controls a Microbit and shows some sensor data.
I am trying to implement asynchronous read and writes to the microbit through my flask backend based on the things I click on the front end.
But when I use flask to run a function I have it gives an error which says
"There is no current event loop in thread"
The function looks like this. It initializes the library I am using for async serial communication.
import aioserial
import asyncio
import serial
def test1():
return aioserial.AioSerial(port='COM5', baudrate = 115200)
print(test1())
When I run this file the output is as expected
AioSerial<id=0x1c5a373ed90, open=True>(port='COM5', baudrate=115200, bytesize=8, parity='N',
stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)
However when I call the same function from a flask function
@app.before_first_request
def startserial():
global aioserialinstance
try:
portaddress = find_comport(PID_MICROBIT, VID_MICROBIT, 115200)
print(portaddress)
aioserialinstance = test1()
except Exception as e:
print(str(e))
print("device not connected or wrong port number")
I get this error
File "C:\Users\adity\Documents\Brbytes Folder\lessons-interactive\2021\Flask-microbit\app.py", line 23, in startserial
aioserialinstance = aioserial.AioSerial(port='COM5', baudrate = 115200)
File "C:\Users\adity\Documents\Brbytes Folder\lessons-interactive\2021\Flask-microbit\venv\Lib\site-packages\aioserial\aioserial.py", line 57, in __init__
self._read_lock: asyncio.Lock = asyncio.Lock()
File "C:\Users\adity\AppData\Local\Programs\Python\Python39\Lib\asyncio\locks.py", line 81, in __init__
self._loop = events.get_event_loop()
File "C:\Users\adity\AppData\Local\Programs\Python\Python39\Lib\asyncio\events.py", line 642, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-2'.
I am not sure what is causing this error when I run it with flask app. When I make some test programs and reading,writing everything works perfectly but on importing these functions into the flask app.py breaks them with this error.
I do not have much knowledge of asyncio and I am completely out of ideas to fix this.
Upvotes: 2
Views: 4585
Reputation: 3836
The error indicates that there in no event loop in not MainThread, for async programs in Python we usually have only one asyncio
loop in MainThread, we do not want more asyncio
loops, since they'll be fighting each other for time and the whole app will be slower and more prone to errors.
If I were you I would use aiohttp
or any other async http framework instead of Flask, otherwise use any other not async library for serial port
.
But how you can get another loop in not MainThread if you want it? Please find example:
import asyncio
from threading import Thread, current_thread
async def async_job():
await asyncio.sleep(5)
print(f"{current_thread().getName()}___Hurray!\n")
def asyncio_wrapper_function():
try:
loop = asyncio.get_event_loop()
except RuntimeError as ex:
print(ex)
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(async_job())
finally:
loop.close()
if __name__ == '__main__':
ths = [
Thread(target=asyncio_wrapper_function, name=f"Th-{i}") for i in range(4)
]
[i.start() for i in ths]
[i.join() for i in ths]
print("All work done!")
Upvotes: 3