]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Document the lifespan event handler parameter (#1110)
authorEmil Melnikov <emilmelnikov@users.noreply.github.com>
Thu, 15 Jul 2021 16:13:43 +0000 (18:13 +0200)
committerGitHub <noreply@github.com>
Thu, 15 Jul 2021 16:13:43 +0000 (17:13 +0100)
Co-authored-by: Thomas Grainger <tagrain@gmail.com>
docs/events.md

index 4f2bce558b3c70360f38433e4fbe6444a700b2c7..c7ed49e9dc28f4d40439edcea77fba747af2a25b 100644 (file)
@@ -37,6 +37,31 @@ registered startup handlers have completed.
 The shutdown handlers will run once all connections have been closed, and
 any in-process background tasks have completed.
 
+A single lifespan asynccontextmanager handler can be used instead of
+separate startup and shutdown handlers:
+
+```python
+import contextlib
+import anyio
+from starlette.applications import Starlette
+
+
+@contextlib.asynccontextmanager
+async def lifespan(app):
+    async with some_async_resource():
+        yield
+
+
+routes = [
+    ...
+]
+
+app = Starlette(routes=routes, lifespan=lifespan)
+```
+
+Consider using [`anyio.create_task_group()`](https://anyio.readthedocs.io/en/stable/tasks.html)
+for managing asynchronious tasks.
+
 ## Running event handlers in tests
 
 You might want to explicitly call into your event handlers in any test setup