"""nex_buddy 服务端入口。 启动:./scripts/dev.sh(开发)/ ./scripts/start.sh(生产,systemd 调用) 健康检查:GET /healthz —— 设备配网页的「测试连通」就是打这个。 """ from __future__ import annotations import logging from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from sqlalchemy import text from app.api import admin, auth, device_v1, devices, media, meta from app.core.config import settings from app.db.session import SessionLocal, dispose_engine from app.services import redis_store, weather logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") log = logging.getLogger("nex_buddy") @asynccontextmanager async def lifespan(app: FastAPI): log.info("starting %s v%s (%s)", settings.app_name, settings.app_version, settings.app_env) if await redis_store.ping(): log.info("redis ok") else: log.warning("redis unreachable: %s", settings.redis_url) yield await redis_store.close() await dispose_engine() app = FastAPI( title="nex_buddy", version=settings.app_version, description="ESP32 圆屏设备服务平台:账号 / 绑定 / 资料 / 天气", lifespan=lifespan, ) app.add_middleware( CORSMiddleware, allow_origins=settings.cors_list, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(auth.router, prefix="/api") app.include_router(devices.router, prefix="/api") app.include_router(admin.router, prefix="/api") app.include_router(media.router, prefix="/api") app.include_router(meta.router, prefix="/api") app.include_router(device_v1.router) @app.exception_handler(Exception) async def unhandled_exception_handler(request, exc): """兜底 500:把完整堆栈打进日志,前端只收到统一错误文案。 uvicorn 默认不把未捕获异常写进重定向的日志文件, 出了 500 又没有堆栈,等于盲猜。 """ log.exception("unhandled error on %s %s", request.method, request.url.path) from fastapi.responses import JSONResponse return JSONResponse(status_code=500, content={"detail": "服务器内部错误(详情见服务端日志)"}) @app.get("/healthz", tags=["meta"]) async def healthz() -> dict: """设备配网页连通性测试用;不要鉴权,也不要吐敏感信息。""" db_ok = False weather_ok = False try: async with SessionLocal() as s: await s.execute(text("select 1")) db_ok = True # 天气是否可用取决于「有效配置」:管理端设置 > Redis > .env weather_ok = await weather.is_configured(s) except Exception as exc: # noqa: BLE001 log.warning("db health failed: %s", exc) redis_ok = await redis_store.ping() return { "ok": db_ok and redis_ok, "service": settings.app_name, "version": settings.app_version, "db": db_ok, "redis": redis_ok, "weather_ready": weather_ok, } @app.get("/", tags=["meta"]) async def root() -> dict: return {"service": settings.app_name, "version": settings.app_version, "docs": "/docs"}