将框架从 Flask 迁移到 FastAPI
主要改动: - 更新依赖:使用 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>
This commit is contained in:
@@ -1,44 +1,56 @@
|
||||
from flask import Flask, send_from_directory
|
||||
from flask_cors import CORS
|
||||
from models import db, Task, TimeRecord
|
||||
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 = Flask(__name__)
|
||||
app = FastAPI(
|
||||
title="WorkList API",
|
||||
description="任务管理和时间追踪API",
|
||||
version="1.0.0"
|
||||
)
|
||||
|
||||
# 配置
|
||||
app.config['SECRET_KEY'] = 'your-secret-key-here-change-in-production'
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///worklist.db'
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
# 配置 CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # 生产环境应该设置具体的域名
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Session配置
|
||||
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
|
||||
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
||||
app.config['PERMANENT_SESSION_LIFETIME'] = 86400 # 24小时
|
||||
# 配置 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
|
||||
)
|
||||
|
||||
# 初始化扩展
|
||||
db.init_app(app)
|
||||
CORS(app, supports_credentials=True) # 允许跨域请求并支持凭证
|
||||
# 初始化数据库
|
||||
init_db()
|
||||
|
||||
# 注册路由
|
||||
app.include_router(api, prefix='/api')
|
||||
|
||||
# 注册蓝图
|
||||
app.register_blueprint(api, url_prefix='/api')
|
||||
|
||||
# 创建数据库表
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
|
||||
# 静态文件服务(用于前端)
|
||||
@app.route('/')
|
||||
def index():
|
||||
return send_from_directory('../frontend', 'index.html')
|
||||
|
||||
@app.route('/<path:filename>')
|
||||
def static_files(filename):
|
||||
return send_from_directory('../frontend', filename)
|
||||
|
||||
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__':
|
||||
app = create_app()
|
||||
app.run(debug=True, host='0.0.0.0', port=5000)
|
||||
import uvicorn
|
||||
uvicorn.run("app:app", host='0.0.0.0', port=5000, reload=True)
|
||||
|
||||
Reference in New Issue
Block a user