kitkat
kitkat

Reputation: 99

Asyncio in Django

I'm using a module that performs asyncio functions to obtain comments through scraping, the code works perfectly in Python scripts but Django does not seem to execute the Asyncio code. I get an error saying

There is no current event loop in thread 'Thread-3'.

def comments(request):
    if request.method == 'POST':
        async def main():
            q = Query('Donald Trump', limit=20)
            async for tw in q.get_comments():
                print(tw)
        loop = asyncio.get_event_loop()
        try:
            loop.run_until_complete(main())
            loop.run_until_complete(loop.shutdown_asyncgens())
        finally:
            loop.close()
        form = CommentForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/index.html')
    else:
        form = CommentForm()
    return render(request, 'index.html', {'form': form})

With some dirty threading work with Asyncio inside of threads, I'm able to execute the loop, but only once.

Upvotes: 6

Views: 1894

Answers (1)

user4815162342
user4815162342

Reputation: 154906

The error message There is no current event loop in thread 'Thread-3'. indicates that you are accessing asyncio from outside the main thread. You can use set_event_loop to set it:

def run_coro(coro):
    try:
        loop = asyncio.get_event_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
    return loop.run_until_complete(coro)

Then, in comments:

run_coro(main())

Upvotes: 6

Related Questions