From e4118304ac1ae304b6c6276eb71d8d3afc4b6857 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 3 Nov 2023 08:21:17 +0100 Subject: [PATCH] [Backport 8.10] Update FastAPI example to use lifespan events (#2360) * Update FastAPI example to use lifespan events (#2356) (cherry picked from commit a94eccce8482631037643eaea0370d3349135ada) * Trigger CI --------- Co-authored-by: Quentin Pradet --- 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 3cc4427ac..0f0b82123 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 -------------