Flask interview question · Most asked
Explain Flask's application context and request context.
Summary
The request context makes request and session available during a request; the application context makes current_app and g available. Both are pushed automatically per request and are stored in context-local storage (contextvars), so these proxies are safe per thread/task.
Longer Answer
Outside a request (CLI scripts, background jobs, tests) you must push an app context with with app.app_context(): before using current_app, extensions like Flask-SQLAlchemy, or url_for. test_request_context() simulates a request. The 'working outside of application context' error means code ran without an active context.
Code Example
from flask import current_app
def nightly_cleanup(app):
with app.app_context():
current_app.logger.info("cleaning up")
db.session.execute(db.delete(Session).where(Session.expired))
db.session.commit()
Key Points
request,session: request contextcurrent_app,g: app context- Context locals via contextvars
- Push contexts manually outside requests
Explanation
Common mistakes
- Accessing
requestin a background thread - Storing request data in module globals
More most-asked Flask questions
- How do Flask sessions work and what are their security implications?
- How do you use SQLAlchemy with Flask (Flask-SQLAlchemy 3.x)?
- What is the application factory pattern in Flask and why use it?
- What is Flask and what does 'microframework' mean?
- What are Blueprints in Flask?
- How does routing work in Flask, including variable rules and HTTP methods?
- How do you access request data and build responses in Flask?
- How do you implement user authentication in Flask?