unis_hrms/app/main.py

150 lines
5.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""UNIS HRMS —— FastAPI 应用入口。
启动顺序:create_all(SQLite 阶段)→ 可选播种 → 挂载路由/中间件/静态资源。
静态资源分两类:
* ``/uploads`` 上传附件目录(``data/uploads``)
* ``/`` ``web/dist`` 的前端构建产物(存在才挂,单容器即可整站部署)
"""
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from .api.v1 import router as v1_router
from .core.config import settings
from .core.errors import register_exception_handlers
from .core.middleware import OperationLogMiddleware, RequestIdMiddleware
from .db.session import engine
from . import models # noqa: F401 -- ensure mappers are registered
log = logging.getLogger("hrms")
@asynccontextmanager
async def lifespan(app: FastAPI):
import asyncio
Path(settings.upload_dir).mkdir(parents=True, exist_ok=True)
if settings.auto_create_schema:
from .db.schema import sync_schema
await sync_schema(engine, is_sqlite=settings.is_sqlite)
log.info("schema ready (%s)", "sqlite" if settings.is_sqlite else "mysql")
if getattr(settings, "auto_seed", False):
from .services.seed import seed_all
async with engine.begin() as conn: # pragma: no cover
pass
await seed_all()
log.info("seed data ready")
else:
# 升级发版后必须自动补齐 RBAC 基线(新权限点 + 新菜单),否则新功能页面
# 在老环境里既看不见菜单、也无法授权 —— 这一步只写 sys_permission/sys_menu,
# 不碰任何业务数据,因此可以每次启动都跑。
await _sync_rbac()
yield
await engine.dispose()
async def _sync_rbac() -> None:
from .services.seed_rbac import sync_rbac
try:
report = await sync_rbac()
except Exception as exc: # pragma: no cover -- 表还没建等场景,不阻断启动
log.warning("RBAC 同步跳过:%s", exc)
return
if report.get("new_permissions") or report.get("menus") or report.get("super_admin_grants"):
# 走 uvicorn 的 logger:项目自身 logger 是 INFO,默认日志级别下看不见,
# 而「升级后菜单没进来」最需要的就是启动日志里这一行确认。
logging.getLogger("uvicorn.error").info(
"RBAC 同步:新增权限点 %s、菜单 %s、超管补授权 %s",
report.get("new_permissions"), report.get("menus"), report.get("super_admin_grants"),
)
def _mount_uploads(app: FastAPI) -> None:
upload_root = Path(settings.upload_dir)
upload_root.mkdir(parents=True, exist_ok=True)
app.mount("/uploads", StaticFiles(directory=str(upload_root)), name="uploads")
def _mount_web_dist(app: FastAPI) -> bool:
"""把前端构建产物(``web/dist``)交给本进程托管。
没构建(只有 vite dev server)时直接跳过,开发模式行为不变。
必须在 ``include_router`` 之后注册:路由按注册顺序匹配,
兜底的 SPA 路由放最后,才不会盖住 /api、/uploads、/docs。
"""
dist = Path(settings.web_dist_dir)
index = dist / "index.html"
if not settings.serve_web_dist or not index.is_file():
return False
hashed_assets = dist / "assets"
if hashed_assets.is_dir():
app.mount("/assets", StaticFiles(directory=str(hashed_assets)), name="assets")
reserved = {"api", "uploads", "docs", "redoc", "openapi.json", "health"}
@app.get("/{full_path:path}", include_in_schema=False)
async def spa(full_path: str) -> FileResponse:
if full_path.split("/", 1)[0] in reserved:
raise HTTPException(status_code=404, detail="Not Found")
target = (dist / full_path).resolve() if full_path else index
if full_path and target.is_file() and target.is_relative_to(dist.resolve()):
return FileResponse(target)
# index 不缓存:前端重新构建后立即生效(文件名带 hash,体积不受影响)
return FileResponse(index, headers={"Cache-Control": "no-cache"})
return True
def create_app() -> FastAPI:
app = FastAPI(
title=settings.app_name,
version=settings.version,
description="现代架构人力资源管理系统:人事档案 / 招聘 / 薪资 / 福利保险 / 员工自助",
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["x-request-id", "content-disposition"],
)
app.add_middleware(OperationLogMiddleware)
app.add_middleware(RequestIdMiddleware)
register_exception_handlers(app)
app.include_router(v1_router, prefix=settings.api_prefix)
@app.get("/health", tags=["公共"], summary="存活探针")
async def health() -> dict:
return {"status": "ok", "app": settings.app_name, "version": settings.version}
_mount_uploads(app)
# SPA 兜底路由必须最后注册(见 _mount_web_dist)
if _mount_web_dist(app):
log.info("serving web dist from %s", settings.web_dist_dir)
return app
app = create_app()