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.
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.
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.
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.
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.
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())
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