Hello Dash community
I have now a substantial Dash application which uses data updated by a callback every 3 seconds and saved into a hidden Div
The update_data callback function calls a function get_data which makes six Rest API calls to six websites synchronously and takes 2 seconds or 330 ms per API call on average
I am hoping to bring my latency down to less than one second and tried to change my get_data function from synchronous to asynchronous with asyncio / await
my new get_data_async function works fine when tested alone and brings down my getting data time as expected
However when I call it from my update_data callback function in my dash application I get the following type of error message:
RuntimeError: There is no current event loop in thread ‘Thread-56’
I suspect callbacks are incompatible with co-routines
Can anyone explain why?
Is there another way to improve my data getting time within dash app?
Thanks
I’m not an Asyncio expert so this is just something I quickly figured out with a little Googling.
The Asyncio Event Loop runs per thread and typically only in the main thread. One way to allow this code to work is to change the policy to run in every theread. Though be aware this may be a lot of overhead and not the correct approach, it might be better to start an event loop only when needed but this at least will let you know if your code works.
I am taking the code from here: https://www.tornadoweb.org/en/stable/_modules/tornado/platform/asyncio.html#AnyThreadEventLoopPolicy
import asyncio
class AnyThreadEventLoopPolicy(asyncio.DefaultEventLoopPolicy):
"""Event loop policy that allows loop creation on any thread."""
def get_event_loop(self) -> asyncio.AbstractEventLoop:
try:
return super().get_event_loop()
except (RuntimeError, AssertionError):
# "There is no current event loop in thread %r"
loop = self.new_event_loop()
self.set_event_loop(loop)
return loop
asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())