Skip to content

Commit

Permalink
Add lifespan docs
Browse files Browse the repository at this point in the history
  • Loading branch information
uSpike committed Mar 13, 2021
1 parent 4620732 commit 8c33c94
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
12 changes: 12 additions & 0 deletions docs/en/docs/advanced/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,15 @@ Here, the `shutdown` event handler function will write a text line `"Application

!!! info
You can read more about these event handlers in <a href="https://www.starlette.io/events/" class="external-link" target="_blank">Starlette's Events' docs</a>.

# lifespan

You can also define a lifespan context as an async generator, instead of using startup and shutdown events.

This is useful when the startup and shutdown events of your application are encompassed in a context manager.

This function must be declared with `async def` and contain one `yield` statement.

```Python hl_lines="8"
{!../../../docs_src/events/tutorial003.py!}
```
15 changes: 15 additions & 0 deletions docs_src/events/tutorial003.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from fastapi import FastAPI


async def lifespan(app):
print("startup")
yield
print("shutdown")


app = FastAPI(lifespan=lifespan)


@app.get("/")
async def hello():
return {"result": "hello world"}

0 comments on commit 8c33c94

Please sign in to comment.