Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 703
kitkat Avatar asked Mar 17 '18 12:03

kitkat


People also ask

Can I use Asyncio in Django?

Django uses asyncio. iscoroutinefunction to test if your view is asynchronous or not. If you implement your own method of returning a coroutine, ensure you set the _is_coroutine attribute of the view to asyncio. coroutines.

What is Asyncio used for?

asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc. asyncio is often a perfect fit for IO-bound and high-level structured network code.

How do I use async view in Django?

http import HttpResponse async def index(request): return HttpResponse("Hello, async Django!") Creating async views in Django is as simple as creating a synchronous view -- all you need to do is add the async keyword. The --reload flag tells Uvicorn to watch your files for changes and reload if it finds any.

Is Django rest asynchronous?

Django REST framework is built on Django, which is a synchronous framework for web applications. If you're already using a synchronous framework like Django, having a synchronous API is less of an issue.


1 Answers

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())
like image 79
user4815162342 Avatar answered Sep 18 '22 14:09

user4815162342