0
0
Djangoframework~30 mins

Async middleware in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Async Middleware in Django
📖 Scenario: You are building a Django web application that needs to log the time taken to process each request asynchronously. This helps improve performance by not blocking the main thread.
🎯 Goal: Create an async middleware in Django that measures and logs the time taken for each HTTP request.
📋 What You'll Learn
Create an async middleware class named TimingMiddleware
Add an async __call__ method to handle requests
Use time.perf_counter() to measure request duration
Log the duration after the response is generated
Ensure the middleware calls the next middleware or view asynchronously
💡 Why This Matters
🌍 Real World
Async middleware helps improve web app performance by handling tasks like logging or authentication without blocking the main thread.
💼 Career
Understanding async middleware is important for building scalable Django applications that efficiently handle many simultaneous users.
Progress0 / 4 steps
1
Create the async middleware class
Create a class called TimingMiddleware in middleware.py with an __init__ method that accepts get_response and stores it as self.get_response.
Django
Need a hint?

The __init__ method stores the next callable in the middleware chain.

2
Add the async __call__ method
Add an async __call__ method to TimingMiddleware that accepts request and returns a response by awaiting self.get_response(request).
Django
Need a hint?

The __call__ method must be async and await the next middleware or view.

3
Measure request processing time
Inside the async __call__ method, import time and use time.perf_counter() to record the start time before awaiting self.get_response(request) and the end time after. Calculate the duration as end - start.
Django
Need a hint?

Use time.perf_counter() to get precise timing before and after the request.

4
Log the request duration
After calculating duration in the async __call__ method, import logging and use logging.info to log the message f"Request took {duration:.4f} seconds". Then return the response.
Django
Need a hint?

Use logging.info to output the duration message.