重写独立dockerfile

This commit is contained in:
2026-05-29 18:19:30 +08:00
parent 823a387118
commit 77bdf56adf
14 changed files with 640 additions and 0 deletions
+88
View File
@@ -0,0 +1,88 @@
import os, sys
from pathlib import Path
src_root = Path(__file__).parent.parent
sys.path.insert(0, str(src_root))
os.chdir(Path(__file__).parent.parent.parent)
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, FileResponse
import asyncio, time
from shared.config.settings import settings
from shared.services.auth_routes import router as auth_router
from shared.utils.logger import setup_logging, get_logger
from shared.database.init_db import init_database
setup_logging()
logger = get_logger(__name__)
app = FastAPI(title="Gemold - 模具分析引擎", version="4.0.0")
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
@app.middleware("http")
async def log_requests(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
duration = time.time() - start_time
if response.status_code >= 400:
logger.warning(f"[HTTP] {request.method} {request.url.path} -> {response.status_code} ({duration:.2f}s)")
return response
@app.on_event("startup")
async def startup_event():
success = await init_database(keep_connected=True)
print(f"[{'OK' if success else 'FAIL'}] 数据库初始化")
try:
from moldinsight.storage.rustfs_storage import rustfs_manager
await rustfs_manager.connect(endpoint=settings.RUSTFS_ENDPOINT, access_key=settings.RUSTFS_ACCESS_KEY, secret_key=settings.RUSTFS_SECRET_KEY, timeout=settings.RUSTFS_TIMEOUT)
print("[OK] RustFS连接成功")
except Exception as e:
print(f"[WARN] RustFS连接失败: {e}")
try:
from shared.services.redis_task_manager import redis_task_manager
await redis_task_manager.connect()
print(f"[{'OK' if redis_task_manager.is_connected else 'WARN'}] Redis")
except Exception as e:
print(f"[WARN] Redis异常: {e}")
@app.on_event("shutdown")
async def shutdown_event():
try:
from shared.services.redis_task_manager import redis_task_manager
await redis_task_manager.disconnect()
except: pass
UPLOAD_DIR = Path("uploads"); UPLOAD_DIR.mkdir(exist_ok=True)
Path("html_output").mkdir(exist_ok=True)
app.mount("/static", StaticFiles(directory=os.path.join(os.getcwd(), "static")), name="static")
app.mount("/html", StaticFiles(directory=os.path.join(os.getcwd(), "html_output")), name="html")
app.include_router(auth_router)
try:
from moldinsight.api import router as moldinsight_router
app.include_router(moldinsight_router, prefix="/api")
except Exception as e:
print(f"[WARN] MoldInsight 路由: {e}")
@app.get("/health")
async def health():
from shared.database.database import db_manager
from sqlalchemy import text
db_ok = False; db_error = None
try:
if not db_manager.is_connected: await db_manager.connect()
async with db_manager.engine.begin() as conn: await conn.execute(text("SELECT 1"))
db_ok = True
except Exception as e: db_error = str(e)
return {"status": "healthy", "service": "moldinsight", "version": "4.0.0", "database_connected": db_ok, "database_error": db_error}
@app.get("/{full_path:path}")
async def spa_fallback(full_path: str):
return FileResponse(os.path.join(os.getcwd(), "static", "index.html"))