Python Asyncio in Django View

前端 未结 4 1409
清歌不尽
清歌不尽 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:12

    You can try my way:

    1. At first you need to create app.py in your app_name folder
    2. Then fill your code:

      async def main(language1, language2): 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) 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

    3. in app_name folder fill your views.py:

      import asyncio from django.http import HttpResponse from . import app

      # Create your views here. def index(request): loop = asyncio.new_event_loop() ss = loop.run_until_complete(app.main(language1, language2)) loop.close() return HttpResponse(ss, content_type='text\plain')

提交回复
热议问题