Switch from on_event to lifespan asynccontextmanager

on_event is now deprecated, and to be replaced with lifespan: https://fastapi.tiangolo.com/advanced/events/
This commit is contained in:
Charles Perrot-Minot
2024-05-12 22:57:14 -07:00
committed by GitHub
parent 91ba6d7552
commit f203d23194

View File

@@ -51,6 +51,9 @@ or
### Quick Start ### Quick Start
```python ```python
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI from fastapi import FastAPI
from starlette.requests import Request from starlette.requests import Request
from starlette.responses import Response from starlette.responses import Response
@@ -74,12 +77,11 @@ async def get_cache():
async def index(): async def index():
return dict(hello="world") return dict(hello="world")
@asynccontextmanager
@app.on_event("startup") async def lifespan(_: FastAPI) -> AsyncIterator[None]:
async def startup():
redis = aioredis.from_url("redis://localhost") redis = aioredis.from_url("redis://localhost")
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache") FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
yield
``` ```
### Initialization ### Initialization