class LoggingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print(f'Request: {request.method} {request.path}')
response = self.get_response(request)
print(f'Response: {response.status_code}')
return responseCoding: Implementing a Simple Logging Middleware
This middleware will only log requests but not responses
This middleware correctly logs both request and response information
This middleware will cause an error because get_response is not defined
This middleware needs to inherit from MiddlewareBase to function
Show answer & explanationAnswer
Correct answer
This middleware correctly logs both request and response information
Explanation
Modern Django middleware uses the __init__ and __call__ methods. The get_response callable is passed to __init__ and called within __call__ to process the request and get the response.
Written by ExamHoot EditorialPublished · Updated
All 30 Django Middleware and Request Processing questions
- 1.What is the primary purpose of Django Middleware?
- 2.In which setting in Django is middleware configured?
- 3.What is the order of execution for middleware methods during request processing?
- 4.Which middleware method is called when an exception occurs in a view?
- 5.What does returning a response object from process_request() do?
- 6.Which built-in Django middleware handles Cross-Site Request Forgery (CSRF) protection?
- 7.What is the purpose of the SessionMiddleware in Django?
- 8.What does the CommonMiddleware middleware do?
- 9.In Django middleware, what does returning None from process_request() indicate?
- 10.Which middleware is responsible for adding User object to the request?
- 11.Understanding Django Middleware Execution Order
- 12.Middleware Methods and Request Processing Flow
- 13.Scenario:
- 14.Understanding process_exception() Middleware Method
- 15.Coding:
- 16.Scenario:
- 17.Understanding Middleware Short-Circuiting with Early Response
- 18.Scenario:
- 19.Understanding Middleware Exception Handling
- 20.Scenario:
- 21.Middleware Execution Order and Request Processing Pipeline
- 22.Custom Middleware Implementation for Request Logging
- 23.Exception Handling in Django Middleware
- 24.Request/Response Modification in Middleware - Hari's Scenario
- 25.Middleware Short-Circuiting and Early Response - Prasath's Scenario
- 26.CORS Middleware Implementation
- 27.Conditional Middleware Processing Based on URL Pattern
- 28.Middleware and Template Context Processing
- 29.Database Connection Management in Middleware
- 30.Middleware Initialization with Settings - Hari's Configuration Scenario
