feat: fastapi-backend mit healthcheck und alembic-basis
- GET /api/health prüft die Datenbankverbindung - SQLite im WAL-Modus unter /data/app.db - Auslieferung des gebauten Frontends mit SPA-Fallback - leere Basis-Migration, Tests mit pytest Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ff666175d0
commit
8e6ef05304
15 files changed
+414
No files matched your search
@@ -0,0 +1,6 @@
|
||||
from importlib.metadata import PackageNotFoundError, version
|
||||
|
||||
try:
|
||||
__version__ = version("lan-clipboard")
|
||||
except PackageNotFoundError: # running from source without install
|
||||
__version__ = "0.0.0"
|
||||
Whitespace-only changes.
@@ -0,0 +1,37 @@
|
||||
import logging
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, Response, status
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import __version__
|
||||
from app.db import get_db
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: Literal["ok", "error"]
|
||||
version: str
|
||||
db: Literal["ok", "error"]
|
||||
|
||||
|
||||
@router.get("/health", response_model=HealthResponse)
|
||||
def health(response: Response, db: Annotated[Session, Depends(get_db)]) -> HealthResponse:
|
||||
try:
|
||||
db.execute(text("SELECT 1"))
|
||||
db_status = "ok"
|
||||
except Exception:
|
||||
logger.exception("Database health check failed")
|
||||
db_status = "error"
|
||||
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
return HealthResponse(
|
||||
status="ok" if db_status == "ok" else "error",
|
||||
version=__version__,
|
||||
db=db_status,
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
data_dir: Path = Path("/data")
|
||||
static_dir: Path = Path("/app/static")
|
||||
log_level: str = "info"
|
||||
|
||||
@property
|
||||
def database_url(self) -> str:
|
||||
return f"sqlite:///{self.data_dir / 'app.db'}"
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,38 @@
|
||||
from collections.abc import Iterator
|
||||
from functools import lru_cache
|
||||
|
||||
from sqlalchemy import Engine, create_engine, event
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
|
||||
def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.close()
|
||||
|
||||
|
||||
def create_db_engine(url: str) -> Engine:
|
||||
engine = create_engine(url, connect_args={"check_same_thread": False})
|
||||
event.listen(engine, "connect", _set_sqlite_pragmas)
|
||||
return engine
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_engine() -> Engine:
|
||||
settings = get_settings()
|
||||
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
return create_db_engine(settings.database_url)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _session_factory() -> sessionmaker[Session]:
|
||||
return sessionmaker(bind=get_engine(), expire_on_commit=False)
|
||||
|
||||
|
||||
def get_db() -> Iterator[Session]:
|
||||
with _session_factory()() as session:
|
||||
yield session
|
||||
@@ -0,0 +1,40 @@
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from app import __version__
|
||||
from app.api import health
|
||||
from app.config import get_settings
|
||||
|
||||
|
||||
def _register_frontend(app: FastAPI, static_dir: Path) -> None:
|
||||
"""Serve the built Vue SPA; unknown non-API paths fall back to index.html."""
|
||||
root = static_dir.resolve()
|
||||
index_file = root / "index.html"
|
||||
|
||||
@app.get("/{path:path}", include_in_schema=False)
|
||||
def spa(path: str) -> FileResponse:
|
||||
if path == "api" or path.startswith("api/") or not index_file.is_file():
|
||||
raise HTTPException(status_code=404)
|
||||
candidate = (root / path).resolve()
|
||||
if path and candidate.is_relative_to(root) and candidate.is_file():
|
||||
return FileResponse(candidate)
|
||||
return FileResponse(index_file, headers={"Cache-Control": "no-cache"})
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
settings = get_settings()
|
||||
app = FastAPI(
|
||||
title="LAN-Clipboard",
|
||||
version=__version__,
|
||||
docs_url="/api/docs",
|
||||
openapi_url="/api/openapi.json",
|
||||
redoc_url=None,
|
||||
)
|
||||
app.include_router(health.router, prefix="/api")
|
||||
_register_frontend(app, settings.static_dir)
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1,5 @@
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
Reference in new issue
Block a user