Search code examples
python-3.6python-asyncioaiohttpdjango-2.0

How to make a couple of async method calls in django2.0


I am a doing a small project and decided to use Django2.0 and python3.6+.

In my django view, I want to call a bunch of REST API and get their results (in any order) and then process my request (saving something to database).

I know the right way to do would be to use aiohttp and define an async method and await on it.

I am confused about get_event_loop() and whether the view method should itself be an async method if it has to await the response from these methods.

Also does Django2.0 itself (being implemented in python3.6+) have a loop that I can just add to?

Here is the view I am envisioning

from rest_framework import generics
from aiohttp import ClientSession
class CreateView(generics.ListCreateAPIView):
  def perform_create(self, serializer):
    await get_rest_response([url1, url2])

async def fetch(url):
  async with session.get(url) as response:
    return await response.read()

async def get_rest_response(urls):
   async with ClientSession() as session:
      for i in range(urls):
        task = asyncio.ensure_future(fetch(url.format(i), session))
        tasks.append(task)
    responses = await asyncio.gather(*tasks)

Solution

  • Technically you can do it by loop.run_until_complete() call:

    class CreateView(generics.ListCreateAPIView):
      def perform_create(self, serializer):
        loop = asyncio.get_event_loop()
        loop.run_until_complete(get_rest_response([url1, url2]))
    

    But I doubt if this approach will significantly speed up your code. Django is a synchronous framework anyway.