-
-
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
Merged
Support lifespan state #2060
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ba1588a
Support lifespan state
Kludex 3e7b804
Copy the state instead of reusing on multiple requests
Kludex 35ecd94
Readd deprecated conditionals
Kludex 246a61f
Apply suggestions from code review
Kludex fa07156
Add test for asynccontextmanager
Kludex c791251
Add test for server not supporting lifespan state but app requiring i…
adriangb b5aac4d
Cutefy Adrian's improvements
Kludex File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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,18 @@ async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None: | |
""" | ||
started = False | ||
app = scope.get("app") | ||
state = scope.get("state") | ||
await receive() | ||
try: | ||
async with self.lifespan_context(app): | ||
lifespan_context: Lifespan | ||
if ( | ||
len(inspect.signature(self.lifespan_context).parameters) == 2 | ||
and state is not None | ||
): | ||
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() | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.