What if you could add security checks once and have them work everywhere automatically?
Why Custom middleware creation in Flask? - Purpose & Use Cases
Imagine you want to check every web request to your Flask app for a special token before processing it.
You try adding this check inside every route function manually.
Manually adding checks in every route is tiring and easy to forget.
This leads to inconsistent security and duplicated code everywhere.
Custom middleware lets you write one piece of code that runs before every request automatically.
This keeps your app clean and secure without repeating yourself.
def route(): if not check_token(): return 'Unauthorized' # route logic
@app.before_request def check_token_middleware(): if not check_token(): return 'Unauthorized'
You can add features like logging, authentication, or error handling globally with one simple middleware.
A website that blocks users without a valid login token from accessing any page by checking the token once in middleware.
Manual checks in every route cause repeated code and mistakes.
Middleware runs code automatically before requests.
Custom middleware keeps your app organized and secure.
Practice
Solution
Step 1: Understand middleware role
Middleware runs code around request processing, before and after Flask handles requests.Step 2: Compare options
Only To run code before and after each request is processed by Flask describes this behavior. Other options describe unrelated tasks.Final Answer:
To run code before and after each request is processed by Flask -> Option AQuick Check:
Middleware purpose = run code around requests [OK]
- Confusing middleware with route creation
- Thinking middleware replaces Flask core
- Mixing middleware with database models
Solution
Step 1: Check middleware class structure
Middleware must accept the app in __init__ and implement __call__ with environ and start_response.Step 2: Validate options
Only class MyMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): return self.app(environ, start_response) matches this pattern correctly. Others miss __call__ or parameters.Final Answer:
Correct middleware class with __init__ and __call__ methods -> Option AQuick Check:
Middleware class needs __call__ method [OK]
- Omitting __call__ method
- Not passing app to __init__
- Using function instead of class
class LoggerMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
print('Before request')
response = self.app(environ, start_response)
print('After request')
return response
app.wsgi_app = LoggerMiddleware(app.wsgi_app)Solution
Step 1: Analyze __call__ method
Prints 'Before request', calls app, then prints 'After request'.Step 2: Understand call order
Both prints happen on each request, before and after app call.Final Answer:
Before request printed, then After request printed -> Option DQuick Check:
Prints before and after app call [OK]
- Thinking only one print runs
- Confusing order of prints
- Assuming prints happen outside __call__
class BadMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, request):
print('Middleware active')
return self.app(request)Solution
Step 1: Check __call__ method signature
WSGI middleware __call__ must accept (environ, start_response), not (request).Step 2: Validate other parts
__init__ is correct, printing is allowed, return inside __call__ is correct.Final Answer:
__call__ method has wrong parameters; should be (environ, start_response) -> Option BQuick Check:
Middleware __call__ signature = (environ, start_response) [OK]
- Using Flask request object instead of WSGI params
- Omitting start_response parameter
- Misplacing return statement
Solution
Step 1: Understand WSGI header modification
Headers are set by calling start_response with status and headers. To add headers, wrap start_response.Step 2: Check options for correct header addition
class HeaderMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None): headers.append(('X-Hello', 'World')) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) wraps start_response to append header before calling original start_response. Others misuse start_response or response object.Final Answer:
Wrap start_response to add header before calling original -> Option CQuick Check:
Add headers by wrapping start_response [OK]
- Calling start_response twice incorrectly
- Trying to modify response object directly in WSGI
- Adding headers to environ instead of response
Ready to prove it?
Pass the test and this pattern moves unknown
