From 8a3e41a5442239bb2da5f2df6cfaaf4683e49f96 Mon Sep 17 00:00:00 2001 From: Emil Melnikov Date: Thu, 15 Jul 2021 18:13:43 +0200 Subject: [PATCH] Document the lifespan event handler parameter (#1110) Co-authored-by: Thomas Grainger --- docs/events.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/events.md b/docs/events.md index 4f2bce55..c7ed49e9 100644 --- a/docs/events.md +++ b/docs/events.md @@ -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