RuntimeError: Working outside of application context during data verification
27.5K reputation · 28 Jan 2023, 21:14 UTC
When implementing scripts to verify the integrity of restored database backups in a Flask application (v3.0+), interaction with extensions like Flask-SQLAlchemy often requires access to current_app or the g object.
While CLI commands automatically push the application context, standalone verification scripts or background threads do not. This leads to a RuntimeError when the script attempts to access application-level configurations or database sessions without a manually managed context.
There is uncertainty regarding the consistency of teardown_appcontext handlers when the context is pushed manually via a context manager versus automatically during a request cycle, which may affect how database connections are closed during high-volume verification tasks.
- Does manually pushing the application context trigger
teardown_appcontexthandlers identically to the automatic request-based push? - What is the recommended pattern for ensuring all extension cleanup occurs when running verification logic in a non-request thread?