51 lines
1.5 KiB
Python
51 lines
1.5 KiB
Python
|
|
"""FastAPI 入口:挂 API + 静态前端。"""
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import logging
|
|||
|
|
import os
|
|||
|
|
from contextlib import asynccontextmanager
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
from fastapi import FastAPI
|
|||
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|||
|
|
from fastapi.staticfiles import StaticFiles
|
|||
|
|
|
|||
|
|
from .api import router
|
|||
|
|
from .config import get_settings
|
|||
|
|
from .db import init_db
|
|||
|
|
|
|||
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|||
|
|
log = logging.getLogger("as-event")
|
|||
|
|
settings = get_settings()
|
|||
|
|
|
|||
|
|
|
|||
|
|
@asynccontextmanager
|
|||
|
|
async def lifespan(app: FastAPI):
|
|||
|
|
# 首次启动自动建表(create_all 只补缺表,安全);生产可用 ddl/own_db_init.sql
|
|||
|
|
if os.getenv("AUTO_CREATE_TABLES", "1") == "1":
|
|||
|
|
try:
|
|||
|
|
init_db()
|
|||
|
|
log.info("自有库建表检查完成")
|
|||
|
|
except Exception as e: # noqa: BLE001
|
|||
|
|
log.warning("建表失败(DB 未就绪?):%s", e)
|
|||
|
|
yield
|
|||
|
|
|
|||
|
|
|
|||
|
|
app = FastAPI(title="A股大事记录 / 择时看板", version="0.1.0", lifespan=lifespan)
|
|||
|
|
|
|||
|
|
app.add_middleware(
|
|||
|
|
CORSMiddleware,
|
|||
|
|
allow_origins=settings.cors_origin_list,
|
|||
|
|
allow_methods=["*"],
|
|||
|
|
allow_headers=["*"],
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
app.include_router(router)
|
|||
|
|
|
|||
|
|
# 静态前端(放在 API 之后,作为兜底挂在根路径)
|
|||
|
|
_frontend = Path(__file__).resolve().parent.parent / "frontend"
|
|||
|
|
if _frontend.is_dir():
|
|||
|
|
app.mount("/", StaticFiles(directory=str(_frontend), html=True), name="frontend")
|
|||
|
|
else:
|
|||
|
|
log.warning("未找到前端目录: %s", _frontend)
|