0
0
Djangoframework~10 mins

Async middleware in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define an async middleware class in Django.

Django
class MyAsyncMiddleware:
    async def __call__(self, request):
        response = await self.[1](request)
        return response
Drag options to blanks, or click blank then click option'
Aprocess_request
Bget_response
Chandle_request
Dprocess_response
Attempts:
3 left
💡 Hint
Common Mistakes
Using synchronous method names like process_request in async middleware
Calling a method that does not exist on the middleware class
2fill in blank
medium

Complete the async middleware __init__ method to store the next callable.

Django
class MyAsyncMiddleware:
    def __init__(self, [1]):
        self.get_response = get_response
Drag options to blanks, or click blank then click option'
Aresponse
Brequest
Cself
Dget_response
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter names like request or response in __init__
Not storing the callable to self
3fill in blank
hard

Fix the error in the async middleware call method to await the response.

Django
class MyAsyncMiddleware:
    async def __call__(self, request):
        response = [1] self.get_response(request)
        return response
Drag options to blanks, or click blank then click option'
Aawait
Basync
Cyield
Dself.
Attempts:
3 left
💡 Hint
Common Mistakes
Calling async functions without await
Using yield or async keywords incorrectly
4fill in blank
hard

Fill both blanks to add async pre- and post-processing in middleware.

Django
class MyAsyncMiddleware:
    async def __call__(self, request):
        await [1](request)
        response = await self.get_response(request)
        await [2](response)
        return response
Drag options to blanks, or click blank then click option'
Aself.pre_process
Bself.post_process
Cself.process_request
Dself.process_response
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing synchronous method names with async middleware
Not awaiting async pre/post processing methods
5fill in blank
hard

Fill all three blanks to create an async middleware that logs request and response.

Django
class LoggingAsyncMiddleware:
    def __init__(self, [1]):
        self.get_response = get_response

    async def __call__(self, request):
        print(f"Request path: {request.[2]")
        response = await self.get_response(request)
        print(f"Response status: {response.[3]")
        return response
Drag options to blanks, or click blank then click option'
Aget_response
Bpath
Cstatus_code
Drequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong attribute names like url or status
Not storing get_response correctly
Not awaiting the async get_response call