Skip to content

Accessing request.state in manually routed function throws: RuntimeError: Working outside of operation context. #2094

@philippdieter

Description

@philippdieter

I am new to connexion so I don't know if I just did not get something right or if it is actually a bug, so I hope someone can help me ether case.

Environment:

$ python -V
Python 3.13.7

$ pip freeze
a2wsgi==1.10.10
anyio==4.11.0
asgiref==3.10.0
attrs==25.4.0
blinker==1.9.0
certifi==2025.10.5
charset-normalizer==3.4.4
click==8.3.0
connexion==3.3.0
Flask==3.1.2
h11==0.16.0
httpcore==1.0.9
httptools==0.7.1
httpx==0.28.1
idna==3.11
inflection==0.5.1
itsdangerous==2.2.0
Jinja2==3.1.6
jsonschema==4.25.1
jsonschema-specifications==2025.9.1
MarkupSafe==3.0.3
python-dotenv==1.1.1
python-multipart==0.0.20
PyYAML==6.0.3
referencing==0.37.0
requests==2.32.5
rpds-py==0.28.0
sniffio==1.3.1
starlette==0.48.0
typing_extensions==4.15.0
urllib3==2.5.0
uvicorn==0.38.0
uvloop==0.22.1
watchfiles==1.1.1
websockets==15.0.1
Werkzeug==3.1.3

Example application:

import contextlib
from pathlib import Path
from connexion import FlaskApp, request

@contextlib.asynccontextmanager
async def lifespan_handler(app):
    print('run at start')
    foo = 'bar'
    yield {'foo': foo}
    print('run at shutdown')

app = FlaskApp(
    __name__,
    lifespan=lifespan_handler
    )

@app.route("/test")
async def route():
    foo = request.state.foo
    print(foo)
    return 'foobar'

if __name__ == "__main__":
    app.run(
        f"{Path(__file__).stem}:app",
        port=8080,
        )

So if I now access the /test endpoint i get the following exception:

RuntimeError("Working outside of operation context. Make sure your app is wrapped in a ContextMiddleware and you're processing a request while accessing the context.")
Traceback (most recent call last):

Full console output with traceback

Moving the same function to its own class and have it accessed by an resolver works just fine. So is there a problem or can this just not work?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions