0 day streak
python / beginner
Snippet

Basic Function-based Middleware

Middleware is a system of hooks that process requests globally before they reach a view and responses after they leave a view.

snippet.py
python
1
2
3
4
5
6
7
def simple_middleware(get_response):
def middleware(request):
# Code here runs before the view
response = get_response(request)
# Code here runs after the view
return response
return middleware
django
Breakdown
1
def simple_middleware(get_response):
The factory function that takes the next middleware or view in line.
2
response = get_response(request)
Calls the next part of the request-response cycle to get the response.
3
return response
Returns the final response back up the middleware chain.