Bird
0
0

You want to create middleware that adds a custom header 'X-Hello: World' to every response. Which code snippet correctly implements this?

hard📝 Application Q15 of 15
Flask - Middleware and Extensions
You want to create middleware that adds a custom header 'X-Hello: World' to every response. Which code snippet correctly implements this?
Aclass HeaderMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): response = self.app(environ, start_response) response.headers['X-Hello'] = 'World' return response
Bclass HeaderMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): start_response('200 OK', [('X-Hello', 'World')]) return self.app(environ, start_response)
Cclass 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)
Dclass HeaderMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['X-Hello'] = 'World' return self.app(environ, start_response)
Step-by-Step Solution
Solution:
  1. Step 1: Understand WSGI header modification

    Headers are set by calling start_response with status and headers. To add headers, wrap start_response.
  2. 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.
  3. Final Answer:

    Wrap start_response to add header before calling original -> Option C
  4. Quick Check:

    Add headers by wrapping start_response [OK]
Quick Trick: Wrap start_response to add headers in middleware [OK]
Common Mistakes:
MISTAKES
  • Calling start_response twice incorrectly
  • Trying to modify response object directly in WSGI
  • Adding headers to environ instead of response

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes