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 context
  • current_app, g: app context
  • Context locals via contextvars
  • Push contexts manually outside requests

Explanation

Common mistakes

  • Accessing request in a background thread
  • Storing request data in module globals

More most-asked Flask questions

← All Flask questions