I'm trying to use asyncio in my Django post processing like:
query : # a query to my model
tasks = []
for record in query:
tasks.append(do_something_with_google_calendar(record))
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
But I just get an error while executing:
loop = asyncio.get_event_loop()
RuntimeError: There is no current event loop in thread 'Thread-17'.
Any ideas?
Thank you in advance
Your original code woun't work since get_event_loop() method is only shortcut to get_event_loop_policy().get_event_loop() which create&return event loop automatically for main thread only. To make it work right you need to explicitly create and set new event loop for each current thread context:
query : # a query to my model
tasks = []
for record in query:
tasks.append(do_something_with_google_calendar(record))
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
You may read more about this stuff here.
It looks that if I do like this, it works:
query : # a query to my model
tasks = []
for record in query:
tasks.append(do_something_with_google_calendar(record))
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
I hope it is stable and it will also work fine in UNIX as it does in Windows
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With