How do you implement a custom middleware in Django?
Instruction: Describe the process of creating and applying custom middleware in a Django application.
Context: This question tests the candidate's understanding of Django's middleware framework and their ability to extend or modify the request/response processing flow.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
A modern middleware factory receives get_response once and returns request-handling behavior. In a synchronous class, __call__ wraps the inner handler: code before it runs on the request path, and code after it runs on the returning response path.
This Django5.2 example measures time until the inner handler returns a response and appends a numeric Server-Timing metric:...