How to run Django api's asynchronously
I have a long-running API in Django. When this long-running API is invoked by user1, the other APIs get blocked for user1 until that long-running API call gets resolved. But at the same time for other users, those APIs work well.
class CreateOrderAPIView(APIView):
def post(self, request):
# Creates order
# Some third-party services are invoked (Takes so long)
return Response(order_data, status=201)
Example
Now, when the above API is called by user1, the other API calls get blocked for user1 until the long-running call is completed. However, the other users can invoke the APIs at the same time.
I don't want to go with the celery/redis approach for my long-running tasks for now.
Is there a way to resolve this issue?
you can utilize Python's built-in asyncio library. You can create an asynchronous function to handle the long-running task and use asyncio.run() to execute it asynchronously within your API view.
EXAMPLE
import asyncio
from rest_framework.response import Response
from rest_framework.views import APIView
class CreateOrderAPIView(APIView):
async def create_order_async(self, request):
# Simulate long-running task
await asyncio.sleep(5) # Example: Simulate a task that takes 5 seconds
# Generate order data
order_data = {"order_id": 123, "status": "created"}
return order_data
async def post(self, request):
# Execute the long-running task asynchronously
order_data = await self.create_order_async(request)
return Response(order_data, status=201)