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:
94
94
95
95
.. code-block :: python
96
96
97
+ import os
98
+ from contextlib import asynccontextmanager
99
+
97
100
from fastapi import FastAPI
98
101
from elasticsearch import AsyncElasticsearch
99
102
100
- app = FastAPI()
101
- es = AsyncElasticsearch()
103
+ ELASTICSEARCH_URL = os.environ[ " ELASTICSEARCH_URL " ]
104
+ es = None
102
105
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
106
111
await es.close()
107
112
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
+
108
122
109
123
Async Helpers
110
124
-------------
You can’t perform that action at this time.
0 commit comments