2023-04-13 Running Tasks Concurrently in Django Asynchronous Views by Mariusz Felisiak ( https://fosstodon.org/@felixxm )

Introduction

Mariusz Felisiak, a Django and Python contributor and a Django Fellow, explores how to use recent async improvements in Django to run multiple async tasks in an asynchronous view!

Django on Fly.io is pretty sweet.

Check out how you can be up and running on Fly.io in just minutes.

Async support has really been improving and expanding in Django!

Since Django 3.0 with the addition of ASGI support (Asynchronous Server Gateway Interface) there has been a steady march of improvements that bring Django closer to having a full asynchronous request-response cycle .

Now we’re to the point where there’s enough foundational support that interesting things are possible for our “normal web apps.”.

This is where it gets really exciting for people! Here we’ll take a look at how we can start using async views with Django .

Reviewing async code can be challenging. So, together, we’ll walk through creating our first asynchronous view in Django.

Buckle-up for our async-journey together!

Brief History of Async Support

The brief timeline for adding async support to Django shows it’s been careful, steady, and intentional.

  • Django 3.0 → ASGI support

  • Django 3.1 → Asynchronous views and middlewares

  • Django 4.0 → Asynchronous API for cache backends

  • Django 4.1 → Asynchronous ORM interface

  • Django 4.2 →Asynchronous streaming responses, asynchronous Model and related manager interfaces, and psycopg version 3 support which provides asynchronous connections and cursors

  • Django 5.0 (currently under development 🏗️) → Asynchronous signal dispatch, coroutine request.auser(), and more (?)

Seeing the trend and what’s under development is exciting !

Problem

With all the excitement around asynchronous web development, you’d like to get some of those benefits in your own Django app.

These are the questions we’re setting out to answer:

  • How do we write an asynchronous view in Django?

  • What can be done asynchronously in Django?

  • How to use Django with ASGI (Asynchronous Server Gateway Interface) servers ?

Solution

We need an existing or new Django project. Here are some great resources for getting started with Django or deploying your Django app to Fly.io.

With a project ready, let’s get started!