Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Backport 8.10] Update FastAPI example to use lifespan events #2360

Merged
merged 2 commits into from
Nov 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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