Python Asyncio in Django View
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)
Django is a synchronous framework so you can't use any async/await
in the views because of there no loop or something like that.
You really can use Django channels library for it, but it will make your views asynchronous under the hood by itself, you don't need to use async
also, just connect the channels a go on coding as you do it before, without any async features.
In this particular case you can simply use the ThreadPoolExecutor
, asyncio is using it under the hood in .run_in_executor
anyway (but also adds redundant lines of code / loop creation etc in your example).
# or likely ProcessPoolExecutor is better for cpu-heavy work
from concurrent.futures import ThreadPoolExecutor, wait
# create the executor outside of the view with the number of workers you may need
executor = ThreadPoolExecutor(max_workers=2)
def reco_ibm(lang):
return(r.recognize_ibm(audio, key, secret language=str(lang), show_all=True))
def djangoview(request, language1, language2):
r = sr.Recognizer()
with sr.AudioFile(path.join(os.getcwd(), "audio.wav")) as source:
audio = r.record(source)
# then use it pretty trivially:
futures = []
for lang in [language1, language2]:
futures.append(executor.submit(reco_ibm, lang)
completed, pending = wait(futures)
# `pending` will always be empty here (see the docs on wait)
result1, result2 = [i.result() for i in completed]
# do whatever you want with results etc.
see https://docs.python.org/3/library/concurrent.futures.html