0
0
Flaskframework~5 mins

Before_request as middleware alternative in Flask - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThe request is retried.
BThe response is ignored and the route handler runs anyway.
CAn error is raised.
DThe response is sent immediately, skipping the route handler.
Which of these is NOT a typical use of @app.before_request?
AModifying the response body after route handler
BLogging request details
CChecking user authentication
DSetting up database connections
In Flask, @app.before_request functions run:
ABefore the route handler
BOnly on GET requests
COnly on POST requests
DAfter the route handler
Which Flask decorator would you use to run code after each request?
A@app.before_request
B@app.after_request
C@app.route
D@app.teardown_request
If you want to run code only for certain routes before the request, what should you do?
AUse a separate middleware class
BUse @app.route with a special flag
CUse @app.before_request and check the request path inside
DUse @app.after_request
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.