Refactor database connection handling in API endpoints
- Removed direct pool checks and replaced them with a centralized database initialization method in `init_db`. - Updated API endpoints in `admin.py`, `collection.py`, `pins.py`, and `watched.py` to ensure the database connection pool is initialized before usage. - Enhanced error handling to raise HTTP exceptions if the database is unavailable. - Improved the `init_db` function in `database.py` to prevent multiple simultaneous initializations using an asyncio lock.
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
"""Collection API endpoints"""
|
||||
from fastapi import APIRouter, Query
|
||||
from typing import List, Optional
|
||||
from app.core.database import pool
|
||||
import json
|
||||
|
||||
router = APIRouter()
|
||||
@@ -15,17 +14,20 @@ async def get_collection_summary(
|
||||
Get collection summary by country and media type.
|
||||
Returns counts per country per media type.
|
||||
"""
|
||||
# Pool should be initialized on startup, but check just in case
|
||||
if not pool:
|
||||
from app.core.database import init_db
|
||||
await init_db()
|
||||
# Ensure pool is initialized
|
||||
from app.core.database import init_db, pool as db_pool
|
||||
await init_db()
|
||||
|
||||
if db_pool is None:
|
||||
from fastapi import HTTPException
|
||||
raise HTTPException(status_code=503, detail="Database not available")
|
||||
|
||||
# Parse types filter
|
||||
type_filter = []
|
||||
if types:
|
||||
type_filter = [t.strip() for t in types.split(",") if t.strip() in ["movie", "show", "music"]]
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with db_pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
# Build query
|
||||
query = """
|
||||
|
||||
Reference in New Issue
Block a user