Flask interview question · Most asked
What request hooks does Flask provide and when do they run?
Summary
before_request runs before each view (returning a response short-circuits), after_request receives and can modify the response, teardown_request/teardown_appcontext always run at the end (even on errors) for cleanup.
Longer Answer
Use before_request for auth checks and loading the current user into g; after_request for headers (CORS, security headers); teardown for closing resources. For WSGI-level middleware (e.g., ProxyFix), wrap app.wsgi_app.
Key Points
before_requestcan short-circuitafter_requestmodifies response- Teardown always runs
- WSGI middleware via
app.wsgi_app
More most-asked Flask questions
- How do you access request data and build responses in Flask?
- How do Flask sessions work and what are their security implications?
- What is the application factory pattern in Flask and why use it?
- What is Flask and what does 'microframework' mean?
- Explain Flask's application context and request context.
- What are Blueprints in Flask?
- How does routing work in Flask, including variable rules and HTTP methods?
- How do you use SQLAlchemy with Flask (Flask-SQLAlchemy 3.x)?