From 342e126be1cb008e80890e103e1529ab0d8cc517 Mon Sep 17 00:00:00 2001 From: Quentin Pradet Date: Thu, 2 Nov 2023 11:55:27 +0400 Subject: [PATCH] Update FastAPI example to use lifespan events (#2356) (cherry picked from commit a94eccce8482631037643eaea0370d3349135ada) --- docs/sphinx/async.rst | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/docs/sphinx/async.rst b/docs/sphinx/async.rst index 76bfce519..5c0aa2505 100644 --- a/docs/sphinx/async.rst +++ b/docs/sphinx/async.rst @@ -94,17 +94,31 @@ For example if using FastAPI that might look like this: .. code-block:: python + import os + from contextlib import asynccontextmanager + from fastapi import FastAPI from elasticsearch import AsyncElasticsearch - app = FastAPI() - es = AsyncElasticsearch() + ELASTICSEARCH_URL = os.environ["ELASTICSEARCH_URL"] + es = None - # This gets called once the app is shutting down. - @app.on_event("shutdown") - async def app_shutdown(): + @asynccontextmanager + async def lifespan(app: FastAPI): + global es + es = AsyncElasticsearch(ELASTICSEARCH_URL) + yield await es.close() + app = FastAPI(lifespan=lifespan) + + @app.get("/") + async def main(): + return await es.info() + +You can run this example by saving it to ``main.py`` and executing +``ELASTICSEARCH_URL=http://localhost:9200 uvicorn main:app``. + Async Helpers -------------