Recall & Review
beginner
What is the purpose of the
@app.before_request decorator in Flask?It registers a function to run before each request. This function can modify the request or perform checks like authentication before the main route handler runs.
Click to reveal answer
intermediate
How does
@app.before_request act as a middleware alternative in Flask?It allows you to run code before every request without creating a separate middleware class. This is simpler and fits Flask's design for request preprocessing.
Click to reveal answer
intermediate
Can you stop a request from continuing in a
@app.before_request function? How?Yes. By returning a response (like a redirect or error message) from the
before_request function, Flask stops processing the request further and sends that response immediately.Click to reveal answer
beginner
What is a common use case for
@app.before_request in Flask apps?Common uses include checking if a user is logged in, setting up database connections, or logging request details before the main route logic runs.
Click to reveal answer
advanced
How does
@app.before_request differ from traditional middleware in other frameworks?Traditional middleware often wraps the request and response cycle as separate components. Flask's
before_request is a simpler hook that runs code before the route handler without wrapping the whole cycle.Click to reveal answer
What happens if a
@app.before_request function returns a response?✗ Incorrect
Returning a response from a before_request function stops further processing and sends that response immediately.
Which of these is NOT a typical use of
@app.before_request?✗ Incorrect
before_request runs before the route handler, so it cannot modify the response body after the handler.
In Flask,
@app.before_request functions run:✗ Incorrect
before_request functions run before the route handler for every request.
Which Flask decorator would you use to run code after each request?
✗ Incorrect
@app.after_request runs after the route handler and can modify the response.
If you want to run code only for certain routes before the request, what should you do?
✗ Incorrect
You can use @app.before_request and inside the function check request.path to run code conditionally.
Explain how
@app.before_request works as a middleware alternative in Flask and give an example use case.Think about what happens before your route code runs.
You got /4 concepts.
Describe how you can stop a request from reaching the route handler using
@app.before_request.Returning something other than None is key.
You got /3 concepts.