2.1 KiB
2.1 KiB
| id | type | title | tags | importance | confidence | created | updated | relations | ||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 8a4ae0ed-5bac-459b-bdd8-d3075bfc108d | fix | Fix: Replace manual db.close() calls with FastAPI middleware in paper-dynasty-database |
|
0.7 | 0.8 | 2026-03-03T05:38:10.354619+00:00 | 2026-03-03T05:38:11.920614+00:00 |
|
Problem
467 manual db.close() calls across 30 router files in app/routers_v2/. Any uncaught exception would leak a Peewee DB connection. Brittle to maintain.
Solution
Added db_session_middleware to app/main.py using FastAPI's @app.middleware("http") decorator:
@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
try:
db.connect(reuse_if_open=True)
response = await call_next(request)
return response
finally:
if not db.is_closed():
db.close()
Used db.connect(reuse_if_open=True) — safe for both SQLite and PooledPostgresqlDatabase (pool returns connection on close).
Removed all db.close() lines from routers with a Python regex script:
re.sub(r'^[ \t]*db\.close\(\)\n', '', content, flags=re.MULTILINE)
Files Changed
app/main.py— added import + middleware (11 lines)app/routers_v2/*.py— removed db.close() from 30 files
Notes
db.close()at end ofdb_engine.py(line 1067) is initialization cleanup — intentionally kept- Some router files now have unused
dbimports (only used for db.close()) — harmless, can clean up later - PR #33 in paper-dynasty-database