{"id":"ea6e7aedc6ef3562","repo":"pallets/flask","slug":"working-outside-of-request-context-attempted-to","errorCode":null,"errorMessage":"Working outside of request context.\n\nAttempted to use functionality that expected an active HTTP request. See the\ndocumentation on request context for more information.","messagePattern":"Working outside of request context\\.\n\nAttempted to use functionality that expected an active HTTP request\\. See the\ndocumentation on request context for more information\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"src/flask/globals.py","lineNumber":51,"sourceCode":"_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 = \"\"\"\\\nWorking outside of request context.\n\nAttempted to use functionality that expected an active HTTP request. See the\ndocumentation on request context for more information.\\\n\"\"\"\nrequest: RequestProxy = LocalProxy(  # type: ignore[assignment]\n    _cv_app, \"request\", unbound_message=_no_req_msg\n)\nsession: SessionMixinProxy = LocalProxy(  # type: ignore[assignment]\n    _cv_app, \"session\", unbound_message=_no_req_msg\n)\n\n\ndef __getattr__(name: str) -> t.Any:\n    import warnings\n\n    if name == \"request_ctx\":\n        warnings.warn(","sourceCodeStart":33,"sourceCodeEnd":69,"githubUrl":"https://github.com/pallets/flask/blob/6a2f545bfd8ed31e19066a299296917e034aca58/src/flask/globals.py#L33-L69","documentation":"The `request` and `session` proxies are LocalProxy objects reading the `request`/`session` attributes off the current AppContext in the `flask.app_ctx` ContextVar (src/flask/globals.py:57-62). If no context is set — or in Flask 3.x if an app context exists but was created without a request — dereferencing them raises this RuntimeError. It exists because request data is per-HTTP-request state that only makes sense while Flask is dispatching a request.","triggerScenarios":"Touching `flask.request` or `flask.session` outside request dispatch: at import time, inside `with app.app_context()` (app context alone has no request), in background threads/async tasks spawned from a view, in Celery tasks, or in a plain script. Also calling code paths that read `request` implicitly, e.g. `url_for` with `_external` relying on request host, or accessing `request.args` in a CLI command.","commonSituations":"Evaluating `request.args.get(...)` as a function default argument or at module level; background jobs trying to read the request that enqueued them; testing view helper functions directly instead of via `app.test_request_context()`; WebSocket/SSE handlers running after the request ended; confusing app context (which `flask shell` provides) with request context.","solutions":["Only access `request`/`session` inside view functions, before/after-request hooks, or template rendering during a request.","In tests or scripts, wrap the code in `with app.test_request_context('/path'): ...` to simulate a request.","For background work, extract the needed request data in the view and pass plain values to the task, or use `@copy_current_request_context` for threads.","Move module-level `request` access into the function body so it evaluates during dispatch."],"exampleFix":"# before\nfrom flask import request\n\ndef get_locale():\n    return request.accept_languages.best  # called from a script -> RuntimeError\n\n# after\nwith app.test_request_context('/', headers={'Accept-Language': 'en'}):\n    locale = get_locale()","handlingStrategy":"type-guard","validationCode":"from flask import has_request_context, request\n\nif has_request_context():\n    user_agent = request.headers.get(\"User-Agent\")\nelse:\n    user_agent = None  # or obtain the data from explicit parameters","typeGuard":"from flask import has_request_context\n\ndef in_request() -> bool:\n    \"\"\"True if request/session proxies are usable.\"\"\"\n    return has_request_context()","tryCatchPattern":"try:\n    ip = request.remote_addr\nexcept RuntimeError:\n    # Not inside an HTTP request (background thread, CLI, import time)\n    ip = None","preventionTips":["Only touch `request`/`session` inside view functions or code called from them; pass values (not the proxies) into helpers and threads.","Guard logging formatters and shared utilities with `has_request_context()` (the pattern Flask's own docs use).","In tests, wrap request-dependent code in `app.test_request_context('/path')`.","Never read `request` at module import time or in `before_first_request`-style startup code."],"tags":["flask","python","request-context","runtime-error"],"analyzedSha":"6a2f545bfd8ed31e19066a299296917e034aca58","analyzedAt":"2026-07-31T19:13:49.921Z","schemaVersion":2}