SoFunction
Updated on 2024-11-16

Using asyncio in Django's Views

set in motion

Django is a synchronous framework, this article is not to make Django into an asynchronous framework. Rather, it's for scenarios where you need to request the http api multiple times in a single view.

A simple example

Example from/questions/44667242/python-asyncio-in-django-view :

def djangoview(request, language1, language2):
 async def main(language1, language2):
  loop = asyncio.get_event_loop()
  r = ()
  with (((), "")) as source:
   audio = (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))
 ()
 return(HttpResponse)

In this example, the two tasks are run in a loop in asyncio, and the HttpResponse is returned when both tasks have completed.

Using asyncio in Django's Views

The above example can now be expanded so that it can be used in a more logical way.

For using asyncio, we usually create a subthread dedicated to the asynchronous task.

Create a separate thread in and run the event loop:

import asyncio
import threading

...
application = get_wsgi_application()

# Create child threads and wait
thread_loop = asyncio.new_event_loop()
def start_loop(loop):
 asyncio.set_event_loop(loop)
 loop.run_forever()

t = (target=start_loop, args=(thread_loop,), daemon=True)
()

Then it's just a matter of dynamically adding tasks to the view:

async def fetch(url):
  async with () as session:
   async with (url) as response:
    text = await ()
    return text

def hello(request):
 from yeezy_bot.wsgi import thread_loop

 fut1 = asyncio.run_coroutine_threadsafe(fetch(url1), thread_loop)
 fut2 = asyncio.run_coroutine_threadsafe(fetch(url2), thread_loop)

 ret1 = ()
 ret2 = ()
 return HttpResponse('')

asyncio.run_coroutine_threadsafe() returns is a Future object, so you can get the result of running the task via (). This approach also handles the sequential ordering of data dependencies in API requests.

This is the whole content of this article.