feat: T03 backend core – FastAPI + DB models + Equipment API + Redis cache + health + tests
- FastAPI app with CORS, lifespan handlers - Pydantic Settings config (DB, Redis, CORS, SMTP, JWT, Rentman) - SQLAlchemy async engine + session (DeclarativeBase) - 6 DB models: EquipmentCache, RentalRequest, RentalRequestItem, Contact, AdminUser, SyncLog - Pydantic schemas: EquipmentItem, EquipmentDetail, PaginatedEquipment, ContactCreate, ContactResponse - Redis cache helper: set/get/delete_pattern, rate limiting, equipment key builders - Equipment router: list (search/category/sort/pagination), detail, categories – all cached - Contact router: POST with Pydantic validation + rate limiting (5/min) - Health router: GET /api/health with DB + Redis status - 28 pytest tests (all pass, 90% coverage) - Dockerfile, requirements.txt, pytest.ini, test_report.md
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
"""Redis cache helper for equipment data and rate limiting."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_cache_client: redis.Redis | None = None
|
||||
|
||||
|
||||
def _build_key(*parts: str) -> str:
|
||||
"""Build a colon-separated Redis key."""
|
||||
return ":".join(part.replace(":", "_") for part in parts)
|
||||
|
||||
|
||||
async def get_cache() -> redis.Redis:
|
||||
"""Return the Redis client singleton, creating it on first use."""
|
||||
global _cache_client
|
||||
if _cache_client is None:
|
||||
_cache_client = redis.from_url(settings.REDIS_URL, decode_responses=True)
|
||||
return _cache_client
|
||||
|
||||
|
||||
async def set_cache(key: str, value: Any, ttl: int = 3600) -> None:
|
||||
"""Store a JSON-serialisable value in Redis with a TTL."""
|
||||
try:
|
||||
client = await get_cache()
|
||||
await client.setex(key, ttl, json.dumps(value))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Cache set failed for key=%s: %s", key, exc)
|
||||
|
||||
|
||||
async def get_cached(key: str) -> Any | None:
|
||||
"""Retrieve and JSON-deserialise a cached value."""
|
||||
try:
|
||||
client = await get_cache()
|
||||
raw = await client.get(key)
|
||||
if raw is None:
|
||||
return None
|
||||
return json.loads(raw)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Cache get failed for key=%s: %s", key, exc)
|
||||
return None
|
||||
|
||||
|
||||
async def delete_pattern(pattern: str) -> None:
|
||||
"""Delete all keys matching a glob pattern."""
|
||||
try:
|
||||
client = await get_cache()
|
||||
async for key in client.scan_iter(match=pattern, count=100):
|
||||
await client.delete(key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Cache delete_pattern failed for pattern=%s: %s", pattern, exc)
|
||||
|
||||
|
||||
async def check_rate_limit(identifier: str, max_requests: int = 5, window: int = 60) -> bool:
|
||||
"""Return True if the identifier is within the rate limit."""
|
||||
try:
|
||||
client = await get_cache()
|
||||
key = _build_key("rate", identifier)
|
||||
count = await client.incr(key)
|
||||
if count == 1:
|
||||
await client.expire(key, window)
|
||||
return count <= max_requests
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Rate limit check failed: %s", exc)
|
||||
return True
|
||||
|
||||
|
||||
async def ping_cache() -> bool:
|
||||
"""Check if Redis is reachable."""
|
||||
try:
|
||||
client = await get_cache()
|
||||
return bool(await client.ping())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def equipment_list_key(page: int, category: str | None, sort: str | None, search: str | None) -> str:
|
||||
"""Build the Redis cache key for an equipment list query."""
|
||||
cat = category or "all"
|
||||
srt = sort or "default"
|
||||
srch = search or "all"
|
||||
return _build_key("equipment", "list", str(page), cat, srt, srch)
|
||||
|
||||
|
||||
def equipment_detail_key(item_id: int) -> str:
|
||||
"""Build the Redis cache key for an equipment detail."""
|
||||
return _build_key("equipment", "detail", str(item_id))
|
||||
|
||||
|
||||
def equipment_categories_key() -> str:
|
||||
"""Build the Redis cache key for the equipment categories list."""
|
||||
return _build_key("equipment", "categories")
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Application configuration via Pydantic Settings."""
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Settings loaded from environment variables."""
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
# Database
|
||||
DATABASE_URL: str = "postgresql+asyncpg://hms:hms@localhost:5432/hms"
|
||||
|
||||
# Redis
|
||||
REDIS_URL: str = "redis://localhost:6379/0"
|
||||
|
||||
# CORS
|
||||
CORS_ORIGINS: str = "https://hms.media-on.de,http://localhost:3000"
|
||||
|
||||
# Rentman
|
||||
RENTMAN_API_TOKEN: str = ""
|
||||
|
||||
# Auth
|
||||
JWT_SECRET: str = "dev-secret-change-me"
|
||||
|
||||
# SMTP
|
||||
SMTP_HOST: str = ""
|
||||
SMTP_PORT: int = 587
|
||||
SMTP_USER: str = ""
|
||||
SMTP_PASSWORD: str = ""
|
||||
SMTP_FROM: str = "info@hms-licht-ton.de"
|
||||
|
||||
# Admin
|
||||
ADMIN_USERNAME: str = "admin"
|
||||
ADMIN_PASSWORD: str = "change_me"
|
||||
|
||||
@property
|
||||
def cors_origins_list(self) -> list[str]:
|
||||
"""Parse CORS_ORIGINS into a list."""
|
||||
return [origin.strip() for origin in self.CORS_ORIGINS.split(",") if origin.strip()]
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""SQLAlchemy async engine and session."""
|
||||
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""Base class for all SQLAlchemy models."""
|
||||
pass
|
||||
|
||||
|
||||
engine = create_async_engine(settings.DATABASE_URL, echo=False, future=True)
|
||||
async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
"""Dependency: yields a database session."""
|
||||
async with async_session() as session:
|
||||
yield session
|
||||
@@ -0,0 +1,41 @@
|
||||
"""FastAPI application entry point."""
|
||||
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.config import settings
|
||||
from app.routers import contact, equipment, health
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Manage application startup and shutdown."""
|
||||
logger.info("HMS Licht & Ton API starting up...")
|
||||
yield
|
||||
logger.info("HMS Licht & Ton API shutting down...")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="HMS Licht & Ton API",
|
||||
description="Backend API for HMS Licht & Ton equipment rental platform.",
|
||||
version="1.0.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origins_list,
|
||||
allow_methods=["GET", "POST"],
|
||||
allow_headers=["*"],
|
||||
allow_credentials=True,
|
||||
)
|
||||
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(equipment.router, prefix="/api")
|
||||
app.include_router(contact.router, prefix="/api")
|
||||
@@ -0,0 +1,9 @@
|
||||
"""SQLAlchemy models package."""
|
||||
|
||||
from app.models.admin_user import AdminUser
|
||||
from app.models.contact import Contact
|
||||
from app.models.equipment import EquipmentCache
|
||||
from app.models.rental_request import RentalRequest, RentalRequestItem
|
||||
from app.models.sync_log import SyncLog
|
||||
|
||||
__all__ = ["AdminUser", "Contact", "EquipmentCache", "RentalRequest", "RentalRequestItem", "SyncLog"]
|
||||
@@ -0,0 +1,19 @@
|
||||
"""AdminUser SQLAlchemy model."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Integer, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class AdminUser(Base):
|
||||
"""Admin user for backend authentication."""
|
||||
|
||||
__tablename__ = "admin_users"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
username: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(server_default=func.now(), nullable=False)
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Contact SQLAlchemy model."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Boolean, Integer, String, Text, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class Contact(Base):
|
||||
"""Contact form submission."""
|
||||
|
||||
__tablename__ = "contacts"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
email: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
phone: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
message: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
privacy_consent: Mapped[bool] = mapped_column(Boolean, nullable=False)
|
||||
email_sent: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(server_default=func.now(), nullable=False)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""EquipmentCache SQLAlchemy model."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import JSON, Boolean, Index, Integer, Numeric, String, Text, func
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class EquipmentCache(Base):
|
||||
"""Cached equipment data imported from Rentman."""
|
||||
|
||||
__tablename__ = "equipment_cache"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
rentman_id: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||
number: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
category: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
|
||||
subcategory: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
specifications: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
images: Mapped[list | None] = mapped_column(JSON, nullable=True)
|
||||
rental_price: Mapped[float | None] = mapped_column(Numeric(10, 2), nullable=True)
|
||||
brand: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
available: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(server_default=func.now(), nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(server_default=func.now(), onupdate=func.now(), nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_equipment_category", "category"),
|
||||
Index("idx_equipment_name", "name"),
|
||||
Index("idx_equipment_number", "number"),
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""RentalRequest and RentalRequestItem SQLAlchemy models."""
|
||||
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Date, ForeignKey, Index, Integer, Numeric, String, Text, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class RentalRequest(Base):
|
||||
"""Rental request submitted by a customer."""
|
||||
|
||||
__tablename__ = "rental_requests"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
reference_number: Mapped[str] = mapped_column(String(32), unique=True, nullable=False)
|
||||
event_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
date_start: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
date_end: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
location: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
person_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
contact_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
contact_company: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
contact_email: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
contact_phone: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
contact_street: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
contact_postalcode: Mapped[str | None] = mapped_column(String(16), nullable=True)
|
||||
contact_city: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False)
|
||||
rentman_request_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
rentman_sync_status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False)
|
||||
rentman_sync_error: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(server_default=func.now(), nullable=False)
|
||||
|
||||
items: Mapped[list["RentalRequestItem"]] = relationship(back_populates="rental_request", cascade="all, delete-orphan")
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_rental_status", "status"),
|
||||
)
|
||||
|
||||
|
||||
class RentalRequestItem(Base):
|
||||
"""Individual equipment line item in a rental request."""
|
||||
|
||||
__tablename__ = "rental_request_items"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
rental_request_id: Mapped[int] = mapped_column(ForeignKey("rental_requests.id", ondelete="CASCADE"), nullable=False)
|
||||
equipment_id: Mapped[int | None] = mapped_column(ForeignKey("equipment_cache.id"), nullable=True)
|
||||
equipment_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
rentman_equipment_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
quantity: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
|
||||
unit_price: Mapped[float | None] = mapped_column(Numeric(10, 2), nullable=True)
|
||||
rentman_sync_status: Mapped[str] = mapped_column(String(32), default="pending", nullable=False)
|
||||
|
||||
rental_request: Mapped["RentalRequest"] = relationship(back_populates="items")
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_rental_items_request", "rental_request_id"),
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""SyncLog SQLAlchemy model."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, Index, Integer, String, Text, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.database import Base
|
||||
|
||||
|
||||
class SyncLog(Base):
|
||||
"""Log entry for equipment sync operations."""
|
||||
|
||||
__tablename__ = "sync_log"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
sync_type: Mapped[str] = mapped_column(String(32), default="equipment", nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
items_processed: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
items_failed: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
started_at: Mapped[datetime] = mapped_column(server_default=func.now(), nullable=False)
|
||||
completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_sync_log_started", "started_at"),
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
"""API routers package."""
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Contact form endpoint with rate limiting."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.cache import check_rate_limit
|
||||
from app.database import get_db
|
||||
from app.models.contact import Contact
|
||||
from app.schemas.contact import ContactCreate, ContactResponse
|
||||
|
||||
router = APIRouter(prefix="/contact", tags=["contact"])
|
||||
|
||||
|
||||
@router.post("", response_model=ContactResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_contact(
|
||||
payload: ContactCreate,
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> ContactResponse:
|
||||
"""Submit a contact form message with rate limiting."""
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
allowed = await check_rate_limit(f"contact:{client_ip}", max_requests=5, window=60)
|
||||
if not allowed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Rate limit exceeded. Please try again later.",
|
||||
)
|
||||
|
||||
contact = Contact(
|
||||
name=payload.name,
|
||||
email=str(payload.email),
|
||||
phone=payload.phone,
|
||||
message=payload.message,
|
||||
privacy_consent=payload.privacy_consent,
|
||||
)
|
||||
db.add(contact)
|
||||
await db.commit()
|
||||
|
||||
return ContactResponse(success=True, message="Kontakt-Anfrage erfolgreich gesendet.")
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Equipment API endpoints with caching and pagination."""
|
||||
|
||||
import math
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.cache import (
|
||||
equipment_categories_key,
|
||||
equipment_detail_key,
|
||||
equipment_list_key,
|
||||
get_cached,
|
||||
set_cache,
|
||||
)
|
||||
from app.database import get_db
|
||||
from app.models.equipment import EquipmentCache
|
||||
from app.schemas.equipment import EquipmentDetail, EquipmentItem, PaginatedEquipment
|
||||
|
||||
router = APIRouter(prefix="/equipment", tags=["equipment"])
|
||||
|
||||
|
||||
@router.get("", response_model=PaginatedEquipment)
|
||||
async def list_equipment(
|
||||
search: str | None = Query(None, description="Search in name"),
|
||||
category: str | None = Query(None, description="Filter by category"),
|
||||
sort: str | None = Query("name_asc", description="Sort order: name_asc, name_desc"),
|
||||
page: int = Query(1, ge=1, description="Page number"),
|
||||
page_size: int = Query(20, ge=1, le=100, description="Items per page"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> PaginatedEquipment:
|
||||
"""Return a paginated, filterable, sortable list of equipment."""
|
||||
cache_key = equipment_list_key(page, category, sort, search)
|
||||
cached = await get_cached(cache_key)
|
||||
if cached is not None:
|
||||
return PaginatedEquipment(**cached)
|
||||
|
||||
query = select(EquipmentCache)
|
||||
count_query = select(func.count(EquipmentCache.id))
|
||||
|
||||
if search:
|
||||
query = query.where(EquipmentCache.name.ilike(f"%{search}%"))
|
||||
count_query = count_query.where(EquipmentCache.name.ilike(f"%{search}%"))
|
||||
|
||||
if category:
|
||||
query = query.where(EquipmentCache.category == category)
|
||||
count_query = count_query.where(EquipmentCache.category == category)
|
||||
|
||||
if sort == "name_desc":
|
||||
query = query.order_by(EquipmentCache.name.desc())
|
||||
else:
|
||||
query = query.order_by(EquipmentCache.name.asc())
|
||||
|
||||
total_result = await db.execute(count_query)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
query = query.offset(offset).limit(page_size)
|
||||
result = await db.execute(query)
|
||||
items = [EquipmentItem.model_validate(row) for row in result.scalars().all()]
|
||||
|
||||
total_pages = math.ceil(total / page_size) if page_size > 0 else 0
|
||||
|
||||
response = PaginatedEquipment(
|
||||
items=items,
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=total_pages,
|
||||
)
|
||||
|
||||
await set_cache(cache_key, response.model_dump(mode="json"), ttl=3600)
|
||||
return response
|
||||
|
||||
|
||||
@router.get("/categories", response_model=list[str])
|
||||
async def list_categories(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> list[str]:
|
||||
"""Return a list of all distinct equipment categories."""
|
||||
cache_key = equipment_categories_key()
|
||||
cached = await get_cached(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
query = select(EquipmentCache.category).distinct().where(EquipmentCache.category.isnot(None)).order_by(EquipmentCache.category.asc())
|
||||
result = await db.execute(query)
|
||||
categories = [row[0] for row in result.all() if row[0]]
|
||||
|
||||
await set_cache(cache_key, categories, ttl=3600)
|
||||
return categories
|
||||
|
||||
|
||||
@router.get("/{equipment_id}", response_model=EquipmentDetail)
|
||||
async def get_equipment(
|
||||
equipment_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> EquipmentDetail:
|
||||
"""Return a single equipment detail by ID."""
|
||||
cache_key = equipment_detail_key(equipment_id)
|
||||
cached = await get_cached(cache_key)
|
||||
if cached is not None:
|
||||
return EquipmentDetail(**cached)
|
||||
|
||||
result = await db.execute(select(EquipmentCache).where(EquipmentCache.id == equipment_id))
|
||||
item = result.scalar_one_or_none()
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Equipment not found",
|
||||
)
|
||||
|
||||
detail = EquipmentDetail.model_validate(item)
|
||||
await set_cache(cache_key, detail.model_dump(mode="json"), ttl=3600)
|
||||
return detail
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Health check endpoint."""
|
||||
|
||||
from fastapi import APIRouter
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from fastapi import Depends
|
||||
|
||||
from app.cache import ping_cache
|
||||
from app.database import get_db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health_check(db: AsyncSession = Depends(get_db)) -> dict:
|
||||
"""Return service health status including DB and Redis connectivity."""
|
||||
db_ok = False
|
||||
try:
|
||||
result = await db.execute(text("SELECT 1"))
|
||||
db_ok = result.scalar() == 1
|
||||
except Exception:
|
||||
db_ok = False
|
||||
|
||||
redis_ok = await ping_cache()
|
||||
|
||||
return {
|
||||
"status": "ok" if (db_ok and redis_ok) else "degraded",
|
||||
"db": "connected" if db_ok else "disconnected",
|
||||
"redis": "connected" if redis_ok else "disconnected",
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Pydantic schemas package."""
|
||||
|
||||
from app.schemas.contact import ContactCreate, ContactResponse
|
||||
from app.schemas.equipment import EquipmentDetail, EquipmentItem, PaginatedEquipment
|
||||
|
||||
__all__ = ["ContactCreate", "ContactResponse", "EquipmentDetail", "EquipmentItem", "PaginatedEquipment"]
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Pydantic schemas for contact form."""
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field, model_validator
|
||||
|
||||
|
||||
class ContactCreate(BaseModel):
|
||||
"""Contact form input schema."""
|
||||
|
||||
name: str = Field(..., min_length=1, max_length=255)
|
||||
email: EmailStr
|
||||
phone: str | None = Field(None, max_length=64)
|
||||
message: str = Field(..., min_length=1, max_length=5000)
|
||||
privacy_consent: bool = Field(..., description="Must be True")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def consent_must_be_true(self) -> "ContactCreate":
|
||||
"""Reject submissions where privacy_consent is not True."""
|
||||
if not self.privacy_consent:
|
||||
raise ValueError("privacy_consent must be True")
|
||||
return self
|
||||
|
||||
|
||||
class ContactResponse(BaseModel):
|
||||
"""Contact form response."""
|
||||
|
||||
success: bool
|
||||
message: str = "Kontakt-Anfrage erfolgreich gesendet."
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Pydantic schemas for equipment endpoints."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class EquipmentItem(BaseModel):
|
||||
"""Equipment item for list responses."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
rentman_id: str
|
||||
name: str
|
||||
number: str | None = None
|
||||
category: str | None = None
|
||||
description: str | None = None
|
||||
image_url: str | None = None
|
||||
rental_price: Decimal | None = None
|
||||
available: bool = True
|
||||
|
||||
|
||||
class EquipmentDetail(BaseModel):
|
||||
"""Equipment detail with full specifications."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
rentman_id: str
|
||||
name: str
|
||||
number: str | None = None
|
||||
category: str | None = None
|
||||
subcategory: str | None = None
|
||||
description: str | None = None
|
||||
specifications: dict | None = None
|
||||
images: list | None = None
|
||||
rental_price: Decimal | None = None
|
||||
brand: str | None = None
|
||||
available: bool = True
|
||||
|
||||
|
||||
class PaginatedEquipment(BaseModel):
|
||||
"""Paginated response for equipment list."""
|
||||
|
||||
items: list[EquipmentItem]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
total_pages: int
|
||||
Reference in New Issue
Block a user