Opened 2 years ago

Last modified 2 years ago

#33611 closed New feature

Allow View subclasses to define async method handlers. — at Version 3

Reported by: Carlton Gibson Owned by: nobody
Component: Generic views Version: 4.0
Severity: Normal Keywords: async, asgi, views
Cc: Andrew Godwin Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Carlton Gibson)

The current topic docs for Async views say this about class-based views:

For a class-based view, this means making its __call__() method an async def (not its __init__() or as_view()).

This isn't really appropriate for Django's class-based views:

  • We don't implement __call__(), rather going via as_view() — for a per-request instance — and then dispatch().
  • Users expect to implement the HTTP method handlers — get(), post(), and so on — rather than these more internal bits.

Ideally we'd allow specifying async def at the method handler level, to allow using await in the handler, and writing views such as this:

    import asyncio
    from django.http import HttpResponse
    from django.views import View

    class AsyncView(View):
        async def get(self, request, *args, **kwargs):
            # Perform io-blocking view-logic using await, sleep for example.
            await asyncio.sleep(1)
            return HttpResponse("Hello async world!")

Change History (3)

comment:1 by Carlton Gibson, 2 years ago

Cc: Andrew Godwin added

comment:2 by Carlton Gibson, 2 years ago

Component: HTTP handlingGeneric views

comment:3 by Carlton Gibson, 2 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top