Bird
0
0

You want to implement async middleware that appends a custom header X-Processed with value True to every response. Which implementation is correct?

hard📝 Application Q8 of 15
Django - Async Django
You want to implement async middleware that appends a custom header X-Processed with value True to every response. Which implementation is correct?
A<pre>class HeaderMiddleware: def __init__(self, get_response): self.get_response = get_response async def __call__(self, request): response = await self.get_response(request) response["X-Processed"] = "True" return response</pre>
B<pre>class HeaderMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response["X-Processed"] = "True" return response</pre>
C<pre>class HeaderMiddleware: def __init__(self, get_response): self.get_response = get_response async def __call__(self, request): response = self.get_response(request) response["X-Processed"] = "True" return response</pre>
D<pre>class HeaderMiddleware: def __init__(self, get_response): self.get_response = get_response async def __call__(self, request): response = await self.get_response(request) response.headers.append(("X-Processed", "True")) return response</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Confirm async __call__ signature

    Async middleware must define async __call__ and await get_response.
  2. Step 2: Check response header modification

    Response headers can be set via dictionary-like access, e.g., response["X-Processed"] = "True".
  3. Step 3: Evaluate options

    class HeaderMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
    
        async def __call__(self, request):
            response = await self.get_response(request)
            response["X-Processed"] = "True"
            return response
    correctly awaits get_response and sets header properly.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Await get_response and set header via response["Header"] [OK]
Quick Trick: Await get_response and set headers via response dict [OK]
Common Mistakes:
MISTAKES
  • Not awaiting get_response in async __call__
  • Using synchronous __call__ for async middleware
  • Incorrectly modifying headers with append method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes