Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asyncio with Django

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

like image 573
vertigo71 Avatar asked Jan 11 '17 15:01

vertigo71


2 Answers

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.

like image 107
Charnel Avatar answered Sep 21 '22 07:09

Charnel


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

like image 36
vertigo71 Avatar answered Sep 18 '22 07:09

vertigo71