0
0
Flaskframework~10 mins

WSGI middleware concept in Flask - 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 a WSGI middleware class that wraps an app.

Flask
class SimpleMiddleware:
    def __init__(self, app):
        self.app = [1]

    def __call__(self, environ, start_response):
        return self.app(environ, start_response)
Drag options to blanks, or click blank then click option'
Aenviron
Bapp
Cstart_response
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning the wrong variable to self.app
Using environ or start_response instead of app
2fill in blank
medium

Complete the code to call the wrapped app inside the middleware __call__ method.

Flask
def __call__(self, environ, start_response):
    # Call the wrapped app
    return self.app([1], start_response)
Drag options to blanks, or click blank then click option'
Aenviron
Bself
Cstart_response
Dapp
Attempts:
3 left
💡 Hint
Common Mistakes
Passing self or start_response as the first argument
Swapping the order of arguments
3fill in blank
hard

Fix the error in the middleware call by completing the code to modify the response headers.

Flask
def __call__(self, environ, start_response):
    def custom_start(status, headers, exc_info=None):
        headers.append(('X-Custom', 'Middleware'))
        return start_response(status, headers, exc_info)

    return self.app(environ, [1])
Drag options to blanks, or click blank then click option'
Astart_response
Bself
Cenviron
Dcustom_start
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the original start_response instead of custom_start
Passing environ instead of a callable
4fill in blank
hard

Fill both blanks to create a middleware that logs the request path and then calls the app.

Flask
def __call__(self, environ, start_response):
    print('Request path:', environ[[1]])
    return self.app(environ, [2])
Drag options to blanks, or click blank then click option'
A'PATH_INFO'
Bstart_response
C'REQUEST_METHOD'
Dcustom_start
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'REQUEST_METHOD' instead of 'PATH_INFO' for the path
Passing custom_start when it is not defined
5fill in blank
hard

Fill all three blanks to create a middleware that adds a header and logs the method.

Flask
def __call__(self, environ, start_response):
    def [1](status, headers, exc_info=None):
        headers.append(('X-Added-By', 'Middleware'))
        return start_response(status, headers, exc_info)

    print('Method:', environ[[2]])
    return self.app(environ, [3])
Drag options to blanks, or click blank then click option'
Acustom_start
B'REQUEST_METHOD'
Dstart_response
Attempts:
3 left
💡 Hint
Common Mistakes
Using start_response instead of custom_start when calling the app
Using 'PATH_INFO' instead of 'REQUEST_METHOD' for the method