Bird
0
0

Which is the correct way to define a middleware class in Flask?

easy📝 Syntax Q3 of 15
Flask - Middleware and Extensions
Which is the correct way to define a middleware class in Flask?
Aapp = Flask() app.middleware = MyMiddleware
Bdef MyMiddleware(app): return app
Cclass MyMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): return self.app(environ, start_response)
Dclass MyMiddleware: def run(self): pass
Step-by-Step Solution
Solution:
  1. Step 1: Recall middleware structure

    Middleware in Flask is a callable class that wraps the WSGI app.
  2. Step 2: Match correct syntax

    The class must implement __init__ to accept app and __call__ to handle requests.
  3. Final Answer:

    class MyMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): return self.app(environ, start_response) -> Option C
  4. Quick Check:

    Middleware class = __init__ + __call__ methods [OK]
Quick Trick: Middleware class must be callable with __call__ method [OK]
Common Mistakes:
MISTAKES
  • Defining middleware as a simple function without __call__
  • Missing __init__ to store app reference
  • Assigning middleware directly to app.middleware attribute

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes