{"id":"c05c367d66614a5c","repo":"pallets/flask","slug":"working-outside-of-application-context-attempted","errorCode":null,"errorMessage":"Working outside of application context.\n\nAttempted to use functionality that expected a current application to be set. To\nsolve this, set up an app context using 'with app.app_context()'. See the\ndocumentation on app context for more information.","messagePattern":"Working outside of application context\\.\n\nAttempted to use functionality that expected a current application to be set\\. To\nsolve this, set up an app context using 'with app\\.app_context\\(\\)'\\. See the\ndocumentation on app context for more information\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/flask/globals.py","lineNumber":33,"sourceCode":"    T = t.TypeVar(\"T\", covariant=True)\n\n    class ProxyMixin(t.Protocol[T]):\n        def _get_current_object(self) -> T: ...\n\n    # These subclasses inform type checkers that the proxy objects look like the\n    # proxied type along with the _get_current_object method.\n    class FlaskProxy(ProxyMixin[Flask], Flask): ...\n\n    class AppContextProxy(ProxyMixin[AppContext], AppContext): ...\n\n    class _AppCtxGlobalsProxy(ProxyMixin[_AppCtxGlobals], _AppCtxGlobals): ...\n\n    class RequestProxy(ProxyMixin[Request], Request): ...\n\n    class SessionMixinProxy(ProxyMixin[SessionMixin], SessionMixin): ...\n\n\n_no_app_msg = \"\"\"\\\nWorking outside of application context.\n\nAttempted to use functionality that expected a current application to be set. To\nsolve this, set up an app context using 'with app.app_context()'. See the\ndocumentation on app context for more information.\\\n\"\"\"\n_cv_app: ContextVar[AppContext] = ContextVar(\"flask.app_ctx\")\napp_ctx: AppContextProxy = LocalProxy(  # type: ignore[assignment]\n    _cv_app, unbound_message=_no_app_msg\n)\ncurrent_app: FlaskProxy = LocalProxy(  # type: ignore[assignment]\n    _cv_app, \"app\", unbound_message=_no_app_msg\n)\ng: _AppCtxGlobalsProxy = LocalProxy(  # type: ignore[assignment]\n    _cv_app, \"g\", unbound_message=_no_app_msg\n)\n\n_no_req_msg = \"\"\"\\","sourceCodeStart":15,"sourceCodeEnd":51,"githubUrl":"https://github.com/pallets/flask/blob/6a2f545bfd8ed31e19066a299296917e034aca58/src/flask/globals.py#L15-L51","documentation":"Flask exposes `current_app`, `g`, and `app_ctx` as werkzeug LocalProxy objects bound to the `flask.app_ctx` ContextVar (src/flask/globals.py:40-48). When no AppContext has been pushed onto that ContextVar, dereferencing the proxy raises this RuntimeError with the configured `unbound_message`. It exists because these globals are context-local: Flask cannot know which application you mean unless an app context is active on the current thread/task.","triggerScenarios":"Accessing `current_app`, `g`, or anything that reads them (e.g. `current_app.config`, extensions like SQLAlchemy's `db.session`, `url_for` without a request) from code running outside `with app.app_context()`: module import time, CLI scripts, background threads, Celery tasks, or APScheduler jobs. Also raised when a thread spawned from a view accesses `current_app`, since ContextVars do not propagate to new threads.","commonSituations":"Running one-off database or seed scripts that import models using `current_app`; Celery/RQ workers whose tasks touch Flask extensions without pushing an app context; accessing `current_app` at module top-level in an app-factory project; unit tests calling code directly without a `with app.app_context()` fixture; background threads started with `threading.Thread` from inside a request.","solutions":["Wrap the failing code in an explicit app context: `with app.app_context(): ...`","In app-factory projects, import/call `create_app()` in your script or worker and push its context before using extensions.","For background threads, pass the real app object (`current_app._get_current_object()`) into the thread and push a context there.","In tests, use a fixture that pushes an app context (e.g. pytest fixture yielding inside `with app.app_context()`).","For Celery, configure a task base class that pushes an app context around each task run."],"exampleFix":"# before\nfrom myapp import db\n\ndef seed():\n    db.session.add(User(name=\"a\"))\n    db.session.commit()\n\n# after\nfrom myapp import create_app, db\n\ndef seed():\n    app = create_app()\n    with app.app_context():\n        db.session.add(User(name=\"a\"))\n        db.session.commit()","handlingStrategy":"validation","validationCode":"from flask import current_app\nfrom flask.globals import app_ctx\n\nif app_ctx:  # an app context is active\n    db_uri = current_app.config[\"SQLALCHEMY_DATABASE_URI\"]\nelse:\n    with app.app_context():\n        db_uri = app.config[\"SQLALCHEMY_DATABASE_URI\"]","typeGuard":"from flask import has_app_context\n\ndef in_app_context() -> bool:\n    \"\"\"True if current_app / g are safe to touch.\"\"\"\n    return has_app_context()","tryCatchPattern":"try:\n    value = current_app.config[\"MY_KEY\"]\nexcept RuntimeError as exc:\n    if \"application context\" in str(exc):\n        with app.app_context():\n            value = app.config[\"MY_KEY\"]\n    else:\n        raise","preventionTips":["Wrap CLI scripts, background jobs, and startup code in `with app.app_context():` before touching current_app, g, or extensions.","Prefer passing the concrete `app` object (or use `app.app_context()`) in workers/Celery tasks instead of relying on the current_app proxy.","Use `has_app_context()` in shared helpers that may run both inside and outside requests.","Use the app factory pattern and push a context explicitly in tests (`app.test_request_context()` or `app.app_context()`)."],"tags":["flask","python","app-context","runtime-error"],"analyzedSha":"6a2f545bfd8ed31e19066a299296917e034aca58","analyzedAt":"2026-07-31T19:13:49.921Z","schemaVersion":2}