CodexBloom - Programming Q&A Platform

Django Async View causes 'Task was destroyed but it is pending' warning when accessing an external API

👀 Views: 3 💬 Answers: 1 📅 Created: 2025-06-08
django asyncio httpx asynchronous Python

I need some guidance on I'm confused about After trying multiple solutions online, I still can't figure this out. I'm relatively new to this, so bear with me... I'm encountering a warning message, 'Task was destroyed but it is pending!', when trying to call an external API from an asynchronous Django view using Django 3.2 and the `httpx` library. The warning appears even though I'm using `async` and `await` properly. Here's what my view looks like: ```python from django.http import JsonResponse from django.views import View import httpx class MyAsyncView(View): async def get(self, request): async with httpx.AsyncClient() as client: response = await client.get('https://api.example.com/data') data = response.json() return JsonResponse(data) ``` I've also tried adding a timeout to the `httpx` call, but the warning still persists: ```python response = await client.get('https://api.example.com/data', timeout=5.0) ``` After investigating, it seems like it might be related to how Django's ASGI server handles tasks. I’ve ensured that I’m using an ASGI compatible server like Daphne. However, I still receive that warning in the logs whenever the view is called. Any suggestions on how to fix this or prevent the warning from appearing? I would appreciate any insights into proper async handling in Django and how to ensure that all tasks are completed before the view returns. This is part of a larger web app I'm building. What are your experiences with this? This is my first time working with Python 3.10.