主要改动: - 更新依赖:使用 fastapi、uvicorn 替代 Flask - 数据库层:从 Flask-SQLAlchemy 迁移到纯 SQLAlchemy - 新增 database.py 管理数据库连接和会话 - 路由层:从 Blueprint 迁移到 APIRouter,添加 Pydantic 模型验证 - 应用层:使用 FastAPI 中间件替代 Flask 插件 - 启动方式:使用 uvicorn 替代 Flask 开发服务器 - 更新 Docker 配置以支持 FastAPI 优势: - 更高的性能和异步支持 - 自动生成 OpenAPI 文档 - 更好的类型安全和数据验证 - 所有 API 端点保持向后兼容 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
57 lines
1.6 KiB
Python
57 lines
1.6 KiB
Python
from fastapi import FastAPI
|
|
from fastapi.staticfiles import StaticFiles
|
|
from fastapi.responses import FileResponse
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from starlette.middleware.sessions import SessionMiddleware
|
|
from database import init_db
|
|
from routes import api
|
|
import os
|
|
|
|
def create_app():
|
|
app = FastAPI(
|
|
title="WorkList API",
|
|
description="任务管理和时间追踪API",
|
|
version="1.0.0"
|
|
)
|
|
|
|
# 配置 CORS
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"], # 生产环境应该设置具体的域名
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# 配置 Session
|
|
app.add_middleware(
|
|
SessionMiddleware,
|
|
secret_key='your-secret-key-here-change-in-production',
|
|
max_age=86400, # 24小时
|
|
same_site='lax',
|
|
https_only=False # 生产环境应设置为True
|
|
)
|
|
|
|
# 初始化数据库
|
|
init_db()
|
|
|
|
# 注册路由
|
|
app.include_router(api, prefix='/api')
|
|
|
|
# 静态文件服务(用于前端)
|
|
frontend_path = os.path.join(os.path.dirname(__file__), '../frontend')
|
|
if os.path.exists(frontend_path):
|
|
@app.get("/")
|
|
async def index():
|
|
return FileResponse(os.path.join(frontend_path, 'index.html'))
|
|
|
|
app.mount("/", StaticFiles(directory=frontend_path, html=True), name="static")
|
|
|
|
return app
|
|
|
|
app = create_app()
|
|
|
|
if __name__ == '__main__':
|
|
import uvicorn
|
|
uvicorn.run("app:app", host='0.0.0.0', port=5000, reload=True)
|