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.