Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Django Ninja's AsyncOperation blocks the response when using asyncio.create_task() or asyncio.ensure_future() #1383

Open
c0dezli opened this issue Jan 6, 2025 · 1 comment

Comments

@c0dezli
Copy link

c0dezli commented Jan 6, 2025

Describe the bug
Django Ninja's AsyncOperation blocks the response when using asyncio.create_task() or asyncio.ensure_future() in an async view. Even though these tasks are meant to run in the background, the operation waits for them to complete before sending the response.

Example code:

@router.post("/generate")
async def generate_daily_summary(request):
  logger.info("Starting tasks")
  asyncio.create_task(background_task_1())
  asyncio.create_task(background_task_2())
  logger.info("Tasks created") # This logs immediately
  return 200, None # Response is delayed until tasks complete

The issue appears to be in AsyncOperation.run() where it awaits the entire view function, including any background tasks created within it.

Versions

  • Python version: 3.12
  • Django version: 5.1
  • Django-Ninja version: 1.3.0
  • Pydantic version: 2.5.2

Proposed Solution
Add support for non-blocking background tasks, or consider adding a decorator or parameter to mark certain tasks as background operations that shouldn't block the response:

@router.post("/generate")
@background_tasks
async def generate_daily_summary(request):
    asyncio.create_task(background_task_1())
    asyncio.create_task(background_task_2())
    return 200, None
@c0dezli
Copy link
Author

c0dezli commented Jan 6, 2025

I’m kinda disappointed by this behavior and would appreciate some clarity. Could you help me understand if I’ve misunderstood something? It seems that this behavior simply defeat the purpose of using an async view.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant