Django ViewSet with async external calls
I have a Django viewset with actions (endpoints). I have to call two services and - since their response times are long - I want to make it asynchronously. For some reason this code executes synchronously (get_bad_things
starts only after get_good_things
finishes).
import asyncio
import requests
from rest_framework import viewsets
from rest_framework.response import Response
class AllThingsViewSet(viewsets.ViewSet):
@action(detail=False, url_path="get_things/")
def get_things(self, request) -> Response:
async def get_good_things(cls):
return requests.get("https://stackoverflow.com/")
async def get_bad_things(cls):
return requests.get("https://stackexchange.com/")
try:
loop = asyncio.get_event_loop()
except RuntimeError:
asyncio.set_event_loop(asyncio.new_event_loop())
loop = asyncio.get_event_loop()
things = loop.run_until_complete(
asyncio.gather(*[get_good_things(self), get_bad_things(self)])
)
return Response(things[0], status=200)
What am I doing wrong? I use gunicorn WSGI.