-
-
Notifications
You must be signed in to change notification settings - Fork 1k
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
base: master
Are you sure you want to change the base?
Conversation
tests/test_routing.py
Outdated
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: |
There was a problem hiding this comment.
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.
It breaks probably one of the most popular patterns: 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 |
What if we bind _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 |
@alex-oleshkevich Would there be a way to move away from the |
|
I've applied your comment, but this doesn't provide the DX that I'm aiming. State is initialized with a |
Due to the limitations of Python's type system, I don't think there will be an elegant way to implement this feature. For now, using TypedDict/dataclass is a good compromise design. |
This is a breaking change.
This is here first for discussion.