Junior — Middle
Have you had experience developing your own middleware in Django or similar frameworks?
sobes.tech AI
Answer from AI
Yes, in Django, you can create custom middleware layers for processing requests and responses at the framework level. Middleware is a class that intercepts requests before they reach views and/or responses before they are sent to the client.
An example of simple middleware that logs the processing time of a request:
import time
class SimpleTimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start_time = time.time()
response = self.get_response(request)
duration = time.time() - start_time
print(f"Request to {request.path} took {duration:.4f} seconds")
return response
To use middleware, you need to add its class to the MIDDLEWARE list in Django settings. This approach allows adding cross-cutting functions such as logging, authentication, error handling, etc.