TellmeStpToGlb/app.py
root 5102bd57e8 feat: 服务化改造STP到GLB转换器
- 🚀 新增FastAPI Web服务支持
-  实现异步任务处理和并发转换
- 📊 添加实时进度追踪(0-100%)
- 🏗️ 重构为模块化架构:core/api/services/utils
- 🔧 完整的任务管理系统和状态追踪
- 📖 自动生成API文档(Swagger/ReDoc)
- 🔄 保持CLI模式100%向后兼容
- 🛡️ 增强错误处理和文件验证
- 📝 更新完整文档(README/CLAUDE.md)

技术栈: FastAPI + uvicorn + pydantic + asyncio
API端点: /health, /api/v1/convert, /api/v1/status, /api/v1/tasks

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-02 09:44:43 +08:00

88 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
FastAPI应用入口
STP到GLB转换服务
"""
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from api.routes import router
from services.task_manager import task_manager
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期管理"""
# 启动时的初始化
print("🚀 STP到GLB转换服务启动中...")
# 启动定期清理任务
cleanup_task = asyncio.create_task(periodic_cleanup())
yield
# 关闭时的清理
print("🛑 STP到GLB转换服务关闭中...")
cleanup_task.cancel()
try:
await cleanup_task
except asyncio.CancelledError:
pass
async def periodic_cleanup():
"""定期清理已完成的任务"""
while True:
try:
await asyncio.sleep(300) # 每5分钟清理一次
task_manager.cleanup_completed_tasks(max_tasks=100)
except asyncio.CancelledError:
break
except Exception as e:
print(f"定期清理任务出错: {e}")
# 创建FastAPI应用
app = FastAPI(
title="STP到GLB转换服务",
description="提供STP格式到GLB格式的3D模型转换服务",
version="1.0.0",
lifespan=lifespan
)
# 配置CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 在生产环境中应该限制具体的域名
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 注册路由
app.include_router(router)
# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
"""全局异常处理器"""
print(f"未处理的异常: {exc}")
return HTTPException(status_code=500, detail="服务器内部错误")
if __name__ == "__main__":
import uvicorn
print("启动STP到GLB转换服务...")
print("API文档地址: http://localhost:8000/docs")
print("健康检查: http://localhost:8000/health")
uvicorn.run(
"app:app",
host="0.0.0.0",
port=8000,
reload=True, # 开发模式生产环境应设为False
log_level="info"
)