|
2 | 2 | import uvicorn |
3 | 3 | from dotenv import load_dotenv |
4 | 4 | from fastapi import FastAPI, Query |
| 5 | +from fastapi import Request |
5 | 6 | from psycopg_pool import ConnectionPool |
| 7 | +from contextlib import asynccontextmanager |
6 | 8 | import os |
7 | 9 |
|
8 | 10 |
|
@@ -86,27 +88,31 @@ def search(pool: ConnectionPool, query: str, top_k: int = 5): |
86 | 88 | ] |
87 | 89 |
|
88 | 90 |
|
89 | | -fastapi_app = FastAPI() |
90 | | - |
91 | | - |
92 | | -@fastapi_app.on_event("startup") |
93 | | -def startup_event(): |
| 91 | +@asynccontextmanager |
| 92 | +def lifespan(app: FastAPI): |
94 | 93 | load_dotenv() |
95 | 94 | 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) |
98 | 104 |
|
99 | 105 |
|
100 | 106 | @fastapi_app.get("/search") |
101 | 107 | def search_endpoint( |
| 108 | + request: Request, |
102 | 109 | q: str = Query(..., description="Search query"), |
103 | 110 | limit: int = Query(5, description="Number of results"), |
104 | 111 | ): |
105 | | - results = search(fastapi_app.state.pool, q, limit) |
| 112 | + pool = request.app.state.pool |
| 113 | + results = search(pool, q, limit) |
106 | 114 | return {"results": results} |
107 | 115 |
|
108 | 116 |
|
109 | 117 | if __name__ == "__main__": |
110 | | - load_dotenv() |
111 | | - cocoindex.init() |
112 | 118 | uvicorn.run(fastapi_app, host="0.0.0.0", port=8080) |
0 commit comments