What is Django Middleware, and how do the process_request and process_response hooks work?
Last updated
Middleware is a layer of hooks that wrap request/response processing globally: each middleware sees the request on the way in and the response on the way out, forming an onion around your views.
Modern middleware is a callable:
Since Django 1.10 it's written as a factory: a callable receiving
get_responseand returning a function that takes arequest.Code before calling
get_response()runs on the way in; code after runs on the way out.
Legacy hook methods still supported:
process_request: runs before URL resolution; returning a response short-circuits the chain.process_response: runs after the view, must return a response object, and runs in reverse order.
Ordering matters: Request phase runs top-to-bottom through
MIDDLEWARE; response phase unwinds bottom-to-top.Common uses: authentication, sessions, CSRF, GZip, security headers.
[lang:python]
def timing_middleware(get_response):
def middleware(request):
# before view (request phase)
response = get_response(request)
# after view (response phase)
return response
return middleware
- https://www.interviewbit.com/django-interview-questions/
- https://www.scribd.com/document/911648753/Headout-Backend-Engineering-Interview-Questions-Bank-CLAUDE
- https://www.uplers.com/
- https://medium.com/@anas-issath/the-django-career-guide-from-junior-to-senior-fea1c3e52aa6
- https://www.quora.com/What-are-some-interview-questions-asked-or-can-be-asked-related-to-Django-and-Python
- https://www.reddit.com/r/developersIndia/
- https://internshala.com/blog/infosys-python-interview-questions/