Python Asyncio in Django View

前端 未结 4 1411
清歌不尽
清歌不尽 2020-12-13 20:52

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
imp         


        
4条回答
  •  醉梦人生
    2020-12-13 21:31

    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)
    

提交回复
热议问题