Skip to content

Allow to pass any object as lifespan state #2944

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Kludex
Copy link
Member

@Kludex Kludex commented May 27, 2025

This is a breaking change.

This is here first for discussion.

async def hello_world(request: Request) -> Response:
# modifications to the state should not leak across requests
assert request.state.count == 0
async def hello_world(request: Request[State]) -> Response:
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test needs to be refactored - I just changed to show the behavior changes.

@alex-oleshkevich
Copy link
Member

It breaks probably one of the most popular patterns: request.state.DEPNAME
For example, a database session middleware may set current session like that

class DbMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        scope["state"]['dbsession'] = "database_connection"
        await self.app(scope, receive, send)

and request it in an endpoint like

async def view(request: Request[LifespanState]):
    return JSONResponse(
        {
            "request_state": request.state.dbsession,
        }
    )

Now it throws AttributeError: 'State' object has no attribute 'dbsession'.
IMO, this breaks too many third-party integrations.

@alex-oleshkevich
Copy link
Member

What if we bind LifespanStateT to State to require all child states to inherit from State? This way we can maintain b/w compatibility and users can provide types?

_LifespanStateT = TypeVar("_LifespanStateT", default=State, bind=State)

class MyState(State):
    key: str
    dbsession: Any

class DbMiddleware:
    async def __call__(self, scope, receive, send):
        scope["state"]['dbsession'] = "database_connection"
        await self.app(scope, receive, send)

async def lifespan_state():
    yield MyState(key='value')

async def view(request: Request[MyState]):
    print(request.state.dbsession) # works
    print(request.state.key) # also works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants