-
-
Notifications
You must be signed in to change notification settings - Fork 856
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
Support lifespan state #2060
Support lifespan state #2060
Changes from all commits
ba1588a
3e7b804
35ecd94
246a61f
fa07156
c791251
b5aac4d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,7 +17,7 @@ | |
from starlette.middleware import Middleware | ||
from starlette.requests import Request | ||
from starlette.responses import PlainTextResponse, RedirectResponse | ||
from starlette.types import ASGIApp, Receive, Scope, Send | ||
from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send, StatelessLifespan | ||
from starlette.websockets import WebSocket, WebSocketClose | ||
|
||
|
||
|
@@ -558,17 +558,25 @@ def wrapper(app: typing.Any) -> _AsyncLiftContextManager: | |
return wrapper | ||
|
||
|
||
_TDefaultLifespan = typing.TypeVar("_TDefaultLifespan", bound="_DefaultLifespan") | ||
|
||
|
||
class _DefaultLifespan: | ||
def __init__(self, router: "Router"): | ||
self._router = router | ||
|
||
async def __aenter__(self) -> None: | ||
await self._router.startup() | ||
await self._router.startup(state=self._state) | ||
|
||
async def __aexit__(self, *exc_info: object) -> None: | ||
await self._router.shutdown() | ||
|
||
def __call__(self: _T, app: object) -> _T: | ||
await self._router.shutdown(state=self._state) | ||
|
||
def __call__( | ||
self: _TDefaultLifespan, | ||
app: object, | ||
state: typing.Optional[typing.Dict[str, typing.Any]], | ||
) -> _TDefaultLifespan: | ||
self._state = state | ||
return self | ||
|
||
|
||
|
@@ -580,9 +588,7 @@ def __init__( | |
default: typing.Optional[ASGIApp] = None, | ||
on_startup: typing.Optional[typing.Sequence[typing.Callable]] = None, | ||
on_shutdown: typing.Optional[typing.Sequence[typing.Callable]] = None, | ||
lifespan: typing.Optional[ | ||
typing.Callable[[typing.Any], typing.AsyncContextManager] | ||
] = None, | ||
lifespan: typing.Optional[Lifespan] = None, | ||
) -> None: | ||
self.routes = [] if routes is None else list(routes) | ||
self.redirect_slashes = redirect_slashes | ||
|
@@ -591,10 +597,7 @@ def __init__( | |
self.on_shutdown = [] if on_shutdown is None else list(on_shutdown) | ||
|
||
if lifespan is None: | ||
self.lifespan_context: typing.Callable[ | ||
[typing.Any], typing.AsyncContextManager | ||
] = _DefaultLifespan(self) | ||
|
||
self.lifespan_context: Lifespan = _DefaultLifespan(self) | ||
elif inspect.isasyncgenfunction(lifespan): | ||
Kludex marked this conversation as resolved.
Show resolved
Hide resolved
|
||
warnings.warn( | ||
"async generator function lifespans are deprecated, " | ||
|
@@ -639,21 +642,31 @@ def url_path_for(self, name: str, **path_params: typing.Any) -> URLPath: | |
pass | ||
raise NoMatchFound(name, path_params) | ||
|
||
async def startup(self) -> None: | ||
async def startup( | ||
self, state: typing.Optional[typing.Dict[str, typing.Any]] | ||
) -> None: | ||
""" | ||
Run any `.on_startup` event handlers. | ||
""" | ||
for handler in self.on_startup: | ||
sig = inspect.signature(handler) | ||
if len(sig.parameters) == 1 and state is not None: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If the state is |
||
handler = functools.partial(handler, state) | ||
if is_async_callable(handler): | ||
await handler() | ||
else: | ||
handler() | ||
|
||
async def shutdown(self) -> None: | ||
async def shutdown( | ||
self, state: typing.Optional[typing.Dict[str, typing.Any]] | ||
) -> None: | ||
""" | ||
Run any `.on_shutdown` event handlers. | ||
""" | ||
for handler in self.on_shutdown: | ||
sig = inspect.signature(handler) | ||
if len(sig.parameters) == 1 and state is not None: | ||
handler = functools.partial(handler, state) | ||
if is_async_callable(handler): | ||
await handler() | ||
else: | ||
|
@@ -666,9 +679,23 @@ async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None: | |
""" | ||
started = False | ||
app = scope.get("app") | ||
state = scope.get("state") | ||
await receive() | ||
lifespan_needs_state = ( | ||
len(inspect.signature(self.lifespan_context).parameters) == 2 | ||
) | ||
server_supports_state = state is not None | ||
if lifespan_needs_state and not server_supports_state: | ||
raise RuntimeError( | ||
'The server does not support "state" in the lifespan scope.' | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I removed the "please change server", and use the created the |
||
) | ||
try: | ||
async with self.lifespan_context(app): | ||
lifespan_context: Lifespan | ||
if lifespan_needs_state: | ||
lifespan_context = functools.partial(self.lifespan_context, state=state) | ||
else: | ||
lifespan_context = typing.cast(StatelessLifespan, self.lifespan_context) | ||
async with lifespan_context(app): | ||
await send({"type": "lifespan.startup.complete"}) | ||
started = True | ||
await receive() | ||
|
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.
At first glance I'm a bit confused about this and the need for a TypeVar.
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.
The reason for the
TypeVar
is that it needed to be bound, as the_state
was introduced here, since theself
is annotated.