Finish database, API, Compare/Detail/Compare Views
This commit is contained in:
59
backend/main.py
Normal file
59
backend/main.py
Normal file
@@ -0,0 +1,59 @@
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from pydantic import BaseModel
|
||||
from database import init_db, get_all_mcus, get_mcu, add_mcu, update_mcu, delete_mcu
|
||||
|
||||
# Pydantic 模型(用于请求体验证)
|
||||
class MCU(BaseModel):
|
||||
name: str
|
||||
core: str
|
||||
frequency: int
|
||||
|
||||
# 初始化 FastAPI
|
||||
app = FastAPI(title="MCU Compare API", version="1.0")
|
||||
|
||||
# 允许跨域
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 初始化数据库
|
||||
init_db()
|
||||
|
||||
# ✅ 1. 获取所有 MCU
|
||||
@app.get("/api/mcus")
|
||||
def read_mcus():
|
||||
return get_all_mcus()
|
||||
|
||||
# ✅ 2. 获取单个 MCU
|
||||
@app.get("/api/mcus/{mcu_id}")
|
||||
def read_mcu(mcu_id: int):
|
||||
mcu = get_mcu(mcu_id)
|
||||
if not mcu:
|
||||
raise HTTPException(status_code=404, detail="MCU not found")
|
||||
return mcu
|
||||
|
||||
# ✅ 3. 创建 MCU
|
||||
@app.post("/api/mcus")
|
||||
def create_mcu(mcu: MCU):
|
||||
add_mcu(mcu.name, mcu.core, mcu.frequency)
|
||||
return {"message": "MCU added successfully"}
|
||||
|
||||
# ✅ 4. 更新 MCU
|
||||
@app.put("/api/mcus/{mcu_id}")
|
||||
def modify_mcu(mcu_id: int, mcu: MCU):
|
||||
if not get_mcu(mcu_id):
|
||||
raise HTTPException(status_code=404, detail="MCU not found")
|
||||
update_mcu(mcu_id, mcu.name, mcu.core, mcu.frequency)
|
||||
return {"message": "MCU updated successfully"}
|
||||
|
||||
# ✅ 5. 删除 MCU
|
||||
@app.delete("/api/mcus/{mcu_id}")
|
||||
def remove_mcu(mcu_id: int):
|
||||
if not get_mcu(mcu_id):
|
||||
raise HTTPException(status_code=404, detail="MCU not found")
|
||||
delete_mcu(mcu_id)
|
||||
return {"message": "MCU deleted successfully"}
|
||||
Reference in New Issue
Block a user