I would like to make two POST requests from an API on a Django view at the same time.
This is how I would do it outside of django.
import asyncio
import speech_recognition as sr
async def main(language1, language2):
loop = asyncio.get_event_loop()
r = sr.Recognizer()
with sr.AudioFile(path.join(os.getcwd(), "audio.wav")) as source:
audio = r.record(source)
def reco_ibm(lang):
return(r.recognize_ibm(audio, key, secret language=lang, show_all=True))
future1 = loop.run_in_executor(None, reco_ibm, str(language1))
future2 = loop.run_in_executor(None, reco_ibm, str(language2))
response1 = await future1
response2 = await future2
loop = asyncio.get_even_loop()
loop.run_until_complete(main("en-US", "es-ES"))
I'm confused about the event loop. How can I do this inside my Django view? Do I need to use nested functions for this?
def ibmaudio_ibm(request, language1, language2):
#Asyncio code here
Edit: How is this even considered a duplicate? Parallel calls and schedulling with crontab are completely different things...
Django has support for writing asynchronous (“async”) views, along with an entirely async-enabled request stack if you are running under ASGI. Async views will still work under WSGI, but with performance penalties, and without the ability to have efficient long-running requests.
An async view function in Django is detected by the annotation async def , which then runs the async view in a thread within its own event loop. This gives the benefit of being able to do and run tasks concurrently inside the async views.
Django itself is synchronous. each HTTP request will be handled completely synchronously. However you have extensions like django-channels ( https://github.com/django/channels ) , which are asynchronous and are intended for web sockets / etc.
Yes it can multi-thread, but generally one uses Celery to do the equivalent. You can read about how in the celery-django tutorial. It is rare that you actually want to force the user to wait for the website.
Solution was to nest the function inside another one.
def djangoview(request, language1, language2):
async def main(language1, language2):
loop = asyncio.get_event_loop()
r = sr.Recognizer()
with sr.AudioFile(path.join(os.getcwd(), "audio.wav")) as source:
audio = r.record(source)
def reco_ibm(lang):
return(r.recognize_ibm(audio, key, secret language=lang, show_all=True))
future1 = loop.run_in_executor(None, reco_ibm, str(language1))
future2 = loop.run_in_executor(None, reco_ibm, str(language2))
response1 = await future1
response2 = await future2
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(language1, language2))
loop.close()
return(HttpResponse)
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