Skip to content

Commit

Permalink
[Backport 8.10] Update FastAPI example to use lifespan events (#2360)
Browse files Browse the repository at this point in the history
* Update FastAPI example to use lifespan events (#2356)

(cherry picked from commit a94eccc)

* Trigger CI

---------

Co-authored-by: Quentin Pradet <[email protected]>
  • Loading branch information
github-actions[bot] and pquentin authored Nov 3, 2023
1 parent d48b428 commit e411830
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions docs/sphinx/async.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------------
Expand Down

0 comments on commit e411830

Please sign in to comment.