Skip to content

Commit aa52a5a

Browse files
Update FastAPI example to use lifespan events (#2356) (#2359)
(cherry picked from commit a94eccc) Co-authored-by: Quentin Pradet <quentin.pradet@elastic.co>
1 parent 5ffc37a commit aa52a5a

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

docs/sphinx/async.rst

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,17 +94,31 @@ For example if using FastAPI that might look like this:
9494

9595
.. code-block:: python
9696
97+
import os
98+
from contextlib import asynccontextmanager
99+
97100
from fastapi import FastAPI
98101
from elasticsearch import AsyncElasticsearch
99102
100-
app = FastAPI()
101-
es = AsyncElasticsearch()
103+
ELASTICSEARCH_URL = os.environ["ELASTICSEARCH_URL"]
104+
es = None
102105
103-
# This gets called once the app is shutting down.
104-
@app.on_event("shutdown")
105-
async def app_shutdown():
106+
@asynccontextmanager
107+
async def lifespan(app: FastAPI):
108+
global es
109+
es = AsyncElasticsearch(ELASTICSEARCH_URL)
110+
yield
106111
await es.close()
107112
113+
app = FastAPI(lifespan=lifespan)
114+
115+
@app.get("/")
116+
async def main():
117+
return await es.info()
118+
119+
You can run this example by saving it to ``main.py`` and executing
120+
``ELASTICSEARCH_URL=http://localhost:9200 uvicorn main:app``.
121+
108122

109123
Async Helpers
110124
-------------

0 commit comments

Comments
 (0)