Skip to content

Commit bd5ec36

Browse files
authored
chore(example): replace deprecated startup event with lifespan (#590)
chore(example): replace deprecated startup event with lifespan
1 parent 4b59fe8 commit bd5ec36

File tree

1 file changed

+16
-10
lines changed
  • examples/fastapi_server_docker

1 file changed

+16
-10
lines changed

examples/fastapi_server_docker/main.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
import uvicorn
33
from dotenv import load_dotenv
44
from fastapi import FastAPI, Query
5+
from fastapi import Request
56
from psycopg_pool import ConnectionPool
7+
from contextlib import asynccontextmanager
68
import os
79

810

@@ -86,27 +88,31 @@ def search(pool: ConnectionPool, query: str, top_k: int = 5):
8688
]
8789

8890

89-
fastapi_app = FastAPI()
90-
91-
92-
@fastapi_app.on_event("startup")
93-
def startup_event():
91+
@asynccontextmanager
92+
def lifespan(app: FastAPI):
9493
load_dotenv()
9594
cocoindex.init()
96-
# Initialize database connection pool
97-
fastapi_app.state.pool = ConnectionPool(os.getenv("COCOINDEX_DATABASE_URL"))
95+
pool = ConnectionPool(os.getenv("COCOINDEX_DATABASE_URL"))
96+
app.state.pool = pool
97+
try:
98+
yield
99+
finally:
100+
pool.close()
101+
102+
103+
fastapi_app = FastAPI(lifespan=lifespan)
98104

99105

100106
@fastapi_app.get("/search")
101107
def search_endpoint(
108+
request: Request,
102109
q: str = Query(..., description="Search query"),
103110
limit: int = Query(5, description="Number of results"),
104111
):
105-
results = search(fastapi_app.state.pool, q, limit)
112+
pool = request.app.state.pool
113+
results = search(pool, q, limit)
106114
return {"results": results}
107115

108116

109117
if __name__ == "__main__":
110-
load_dotenv()
111-
cocoindex.init()
112118
uvicorn.run(fastapi_app, host="0.0.0.0", port=8080)

0 commit comments

Comments
 (0)