-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
use an async context manager factory for lifespan #1227
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
Merged
graingert
merged 8 commits into
Kludex:master
from
graingert:use-a-context-manager-factory-for-lifespan
Jul 3, 2021
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
03832bd
use an async context manager factory for lifespan
graingert 13f8fe1
simplify asynccontextmanager upgrading
graingert 68f9606
make tests pass
graingert e8c3afb
get last bit of coverage
graingert 4cc2697
narrow contextlib2 dep
graingert 83dc724
Merge branch 'master' into use-a-context-manager-factory-for-lifespan
graingert 1aed67d
use @asynccontextmanager in test_use_testclient_as_contextmanager
graingert cedceb4
improve lifespan context deprecation warnings
graingert File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 | ||||
|---|---|---|---|---|---|---|
| @@ -1,9 +1,13 @@ | ||||||
| import asyncio | ||||||
| import contextlib | ||||||
| import functools | ||||||
| import inspect | ||||||
| import re | ||||||
| import sys | ||||||
| import traceback | ||||||
| import types | ||||||
| import typing | ||||||
| import warnings | ||||||
| from enum import Enum | ||||||
|
|
||||||
| from starlette.concurrency import run_in_threadpool | ||||||
|
|
@@ -15,6 +19,11 @@ | |||||
| from starlette.types import ASGIApp, Receive, Scope, Send | ||||||
| from starlette.websockets import WebSocket, WebSocketClose | ||||||
|
|
||||||
| if sys.version_info >= (3, 7): | ||||||
| from contextlib import asynccontextmanager # pragma: no cover | ||||||
| else: | ||||||
| from contextlib2 import asynccontextmanager # pragma: no cover | ||||||
|
|
||||||
|
|
||||||
| class NoMatchFound(Exception): | ||||||
| """ | ||||||
|
|
@@ -470,6 +479,51 @@ def __eq__(self, other: typing.Any) -> bool: | |||||
| ) | ||||||
|
|
||||||
|
|
||||||
| _T = typing.TypeVar("_T") | ||||||
|
|
||||||
|
|
||||||
| class _AsyncLiftContextManager(typing.AsyncContextManager[_T]): | ||||||
| def __init__(self, cm: typing.ContextManager[_T]): | ||||||
| self._cm = cm | ||||||
|
|
||||||
| async def __aenter__(self) -> _T: | ||||||
| return self._cm.__enter__() | ||||||
|
|
||||||
| async def __aexit__( | ||||||
| self, | ||||||
| exc_type: typing.Optional[typing.Type[BaseException]], | ||||||
| exc_value: typing.Optional[BaseException], | ||||||
| traceback: typing.Optional[types.TracebackType], | ||||||
| ) -> typing.Optional[bool]: | ||||||
| return self._cm.__exit__(exc_type, exc_value, traceback) | ||||||
|
|
||||||
|
|
||||||
| def _wrap_gen_lifespan_context( | ||||||
| lifespan_context: typing.Callable[[typing.Any], typing.Generator] | ||||||
| ) -> typing.Callable[[typing.Any], typing.AsyncContextManager]: | ||||||
| cmgr = contextlib.contextmanager(lifespan_context) | ||||||
|
|
||||||
| @functools.wraps(cmgr) | ||||||
| def wrapper(app: typing.Any) -> _AsyncLiftContextManager: | ||||||
| return _AsyncLiftContextManager(cmgr(app)) | ||||||
|
|
||||||
| return wrapper | ||||||
|
|
||||||
|
|
||||||
| class _DefaultLifespan: | ||||||
| def __init__(self, router: "Router"): | ||||||
| self._router = router | ||||||
|
|
||||||
| async def __aenter__(self) -> None: | ||||||
| await self._router.startup() | ||||||
|
|
||||||
| async def __aexit__(self, *exc_info: object) -> None: | ||||||
| await self._router.shutdown() | ||||||
|
|
||||||
| def __call__(self: _T, app: object) -> _T: | ||||||
| return self | ||||||
|
|
||||||
|
|
||||||
| class Router: | ||||||
| def __init__( | ||||||
| self, | ||||||
|
|
@@ -478,20 +532,39 @@ def __init__( | |||||
| default: ASGIApp = None, | ||||||
| on_startup: typing.Sequence[typing.Callable] = None, | ||||||
| on_shutdown: typing.Sequence[typing.Callable] = None, | ||||||
| lifespan: typing.Callable[[typing.Any], typing.AsyncGenerator] = None, | ||||||
| lifespan: typing.Callable[[typing.Any], typing.AsyncContextManager] = None, | ||||||
| ) -> None: | ||||||
| self.routes = [] if routes is None else list(routes) | ||||||
| self.redirect_slashes = redirect_slashes | ||||||
| self.default = self.not_found if default is None else default | ||||||
| self.on_startup = [] if on_startup is None else list(on_startup) | ||||||
| self.on_shutdown = [] if on_shutdown is None else list(on_shutdown) | ||||||
|
|
||||||
| async def default_lifespan(app: typing.Any) -> typing.AsyncGenerator: | ||||||
| await self.startup() | ||||||
| yield | ||||||
| await self.shutdown() | ||||||
| if lifespan is None: | ||||||
| self.lifespan_context: typing.Callable[ | ||||||
| [typing.Any], typing.AsyncContextManager | ||||||
| ] = _DefaultLifespan(self) | ||||||
|
|
||||||
| self.lifespan_context = default_lifespan if lifespan is None else lifespan | ||||||
| elif inspect.isasyncgenfunction(lifespan): | ||||||
| warnings.warn( | ||||||
| "async generator function lifespans are deprecated, " | ||||||
| "use an @contextlib.asynccontextmanager function instead", | ||||||
|
Contributor
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 now read this like it should be "a contextlib..."
Suggested change
Contributor
Author
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 read this as |
||||||
| DeprecationWarning, | ||||||
| ) | ||||||
| self.lifespan_context = asynccontextmanager( | ||||||
|
graingert marked this conversation as resolved.
|
||||||
| lifespan, # type: ignore[arg-type] | ||||||
| ) | ||||||
| elif inspect.isgeneratorfunction(lifespan): | ||||||
| warnings.warn( | ||||||
| "generator function lifespans are deprecated, " | ||||||
| "use an @contextlib.asynccontextmanager function instead", | ||||||
| DeprecationWarning, | ||||||
| ) | ||||||
| self.lifespan_context = _wrap_gen_lifespan_context( | ||||||
| lifespan, # type: ignore[arg-type] | ||||||
| ) | ||||||
| else: | ||||||
| self.lifespan_context = lifespan | ||||||
|
|
||||||
| async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None: | ||||||
| if scope["type"] == "websocket": | ||||||
|
|
@@ -541,25 +614,19 @@ async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None: | |||||
| Handle ASGI lifespan messages, which allows us to manage application | ||||||
| startup and shutdown events. | ||||||
| """ | ||||||
| first = True | ||||||
| started = False | ||||||
| app = scope.get("app") | ||||||
| await receive() | ||||||
| try: | ||||||
| if inspect.isasyncgenfunction(self.lifespan_context): | ||||||
| async for item in self.lifespan_context(app): | ||||||
| assert first, "Lifespan context yielded multiple times." | ||||||
| first = False | ||||||
| await send({"type": "lifespan.startup.complete"}) | ||||||
| await receive() | ||||||
| else: | ||||||
| for item in self.lifespan_context(app): # type: ignore | ||||||
| assert first, "Lifespan context yielded multiple times." | ||||||
| first = False | ||||||
| await send({"type": "lifespan.startup.complete"}) | ||||||
| await receive() | ||||||
| async with self.lifespan_context(app): | ||||||
| await send({"type": "lifespan.startup.complete"}) | ||||||
| started = True | ||||||
| await receive() | ||||||
| except BaseException: | ||||||
| if first: | ||||||
| exc_text = traceback.format_exc() | ||||||
| exc_text = traceback.format_exc() | ||||||
| if started: | ||||||
| await send({"type": "lifespan.shutdown.failed", "message": exc_text}) | ||||||
| else: | ||||||
| await send({"type": "lifespan.startup.failed", "message": exc_text}) | ||||||
| raise | ||||||
| else: | ||||||
|
|
||||||
This file contains hidden or 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 hidden or 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 hidden or 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.
Uh oh!
There was an error while loading. Please reload this page.