File tree Expand file tree Collapse file tree 1 file changed +19
-5
lines changed Expand file tree Collapse file tree 1 file changed +19
-5
lines changed Original file line number Diff line number Diff 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
109123Async Helpers
110124-------------
You can’t perform that action at this time.
0 commit comments