0
0
Djangoframework~5 mins

Async middleware in Django

Choose your learning style9 modes available
Introduction

Async middleware lets your Django app handle tasks without waiting, making it faster and smoother.

When you want to handle many user requests at the same time without slowing down.
When you need to do background tasks like logging or checking user info without delay.
When your app talks to other services and you want to wait for them without blocking.
When you want to improve performance for real-time features like chat or notifications.
Syntax
Django
class MyAsyncMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    async def __call__(self, request):
        # Code before view
        response = await self.get_response(request)
        # Code after view
        return response

The middleware class must have an async __call__ method.

Use await to call the next middleware or view asynchronously.

Examples
This middleware prints messages before and after the view runs, using async calls.
Django
class SimpleAsyncMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    async def __call__(self, request):
        print('Before view')
        response = await self.get_response(request)
        print('After view')
        return response
This middleware adds a custom header to every response asynchronously.
Django
class AsyncHeaderMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    async def __call__(self, request):
        response = await self.get_response(request)
        response['X-Custom-Header'] = 'Hello'
        return response
Sample Program

This middleware logs the request path before the view runs and logs the response status after the view finishes, all done asynchronously.

Django
class AsyncLoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    async def __call__(self, request):
        print(f'Handling request path: {request.path}')
        response = await self.get_response(request)
        print(f'Response status: {response.status_code}')
        return response
OutputSuccess
Important Notes

Async middleware works only if your Django app supports async views and async server.

Make sure to use await when calling the next middleware or view to avoid blocking.

Async middleware can improve performance but test carefully to avoid unexpected bugs.

Summary

Async middleware lets Django handle requests without waiting, improving speed.

Define an async __call__ method and use await inside it.

Use async middleware for tasks like logging, headers, or calling other services.