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:
@@ -3,7 +3,7 @@ from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
from app.core.database import pool
|
||||
from app.core.database import init_db, pool as db_pool
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -16,12 +16,11 @@ class PinCreate(BaseModel):
|
||||
@router.get("")
|
||||
async def list_pins():
|
||||
"""List all manual pins"""
|
||||
# Pool should be initialized on startup
|
||||
if not pool:
|
||||
from app.core.database import init_db
|
||||
await init_db()
|
||||
await init_db()
|
||||
if db_pool is None:
|
||||
raise HTTPException(status_code=503, detail="Database not available")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with db_pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
query = """
|
||||
SELECT id, country_code, label, pinned_at
|
||||
@@ -46,12 +45,11 @@ async def list_pins():
|
||||
@router.post("")
|
||||
async def create_pin(pin: PinCreate):
|
||||
"""Create a new manual pin"""
|
||||
# Pool should be initialized on startup
|
||||
if not pool:
|
||||
from app.core.database import init_db
|
||||
await init_db()
|
||||
await init_db()
|
||||
if db_pool is None:
|
||||
raise HTTPException(status_code=503, detail="Database not available")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with db_pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
query = """
|
||||
INSERT INTO moviemap.manual_pin (country_code, label)
|
||||
@@ -68,12 +66,11 @@ async def create_pin(pin: PinCreate):
|
||||
@router.delete("/{pin_id}")
|
||||
async def delete_pin(pin_id: UUID):
|
||||
"""Delete a manual pin"""
|
||||
# Pool should be initialized on startup
|
||||
if not pool:
|
||||
from app.core.database import init_db
|
||||
await init_db()
|
||||
await init_db()
|
||||
if db_pool is None:
|
||||
raise HTTPException(status_code=503, detail="Database not available")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with db_pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
query = "DELETE FROM moviemap.manual_pin WHERE id = %s RETURNING id"
|
||||
await cur.execute(query, (str(pin_id),))
|
||||
|
||||
Reference in New Issue
Block a user