0
0
Flaskframework~10 mins

Teardown hooks 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 register a teardown function in Flask.

Flask
from flask import Flask
app = Flask(__name__)

@app.[1]()
def cleanup(exception=None):
    print("Cleaning up after request")
Drag options to blanks, or click blank then click option'
Abefore_request
Bteardown_request
Croute
Dafter_request
Attempts:
3 left
💡 Hint
Common Mistakes
Using @app.before_request instead of @app.teardown_request
Using @app.after_request which does not run on exceptions
2fill in blank
medium

Complete the code to access the exception object in a teardown function.

Flask
@app.teardown_request
def cleanup([1]=None):
    if [1]:
        print(f"Exception occurred: [1]")
Drag options to blanks, or click blank then click option'
Aexception=None
Bexception
Cexc
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Not providing a default value for the exception argument
Using a different argument name without default
3fill in blank
hard

Fix the error in the teardown function registration.

Flask
def cleanup(exception=None):
    print("Cleaning up")

app.[1](cleanup)
Drag options to blanks, or click blank then click option'
Abefore_request
Bafter_request
Cteardown_request
Droute
Attempts:
3 left
💡 Hint
Common Mistakes
Using app.before_request(cleanup) instead
Using app.route(cleanup) which is for URL routes
4fill in blank
hard

Fill both blanks to create a teardown function that closes a database connection.

Flask
@app.[1]()
def close_db([2]=None):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()
Drag options to blanks, or click blank then click option'
Ateardown_request
Bbefore_request
Cexception
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Using before_request decorator
Using wrong argument name like error
5fill in blank
hard

Fill all three blanks to register a teardown function that logs errors and cleans up resources.

Flask
@app.[1]()
def teardown([2]=None):
    if [2]:
        app.logger.error(f"Error: [2]")
    cleanup_resources()
Drag options to blanks, or click blank then click option'
Ateardown_request
Bexception
Dbefore_request
Attempts:
3 left
💡 Hint
Common Mistakes
Using before_request decorator
Not using the exception argument properly