iT邦幫忙

0

Day 10 - CRUD 實戰 (一):將資料真實寫入資料庫 (Create)

  • 分享至 

  • xImage
  •  

前面幾天我們把 Pydantic 資料驗證、SQLAlchemy 資料表模型,以及最重要的資料庫依賴注入都準備好了。今天終於要進入重頭戲:CRUD 操作。首先第一步就是新增資料 (Create)。

在寫 API 時,我們通常會建立一個 schemas.py 來專門放 Pydantic 模型,跟 models.py 裡的 SQLAlchemy 模型區分開來。假設我們已經有一個 Pydantic 模型叫做 ItemCreate,負責接收前端傳來的 name, description, price。

現在回到 main.py,我們把新增商品的 API 加上真實的資料庫操作:

from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
import models
from database import engine, SessionLocal
from pydantic import BaseModel

app = FastAPI()

class ItemCreate(BaseModel):
name: str
description: str | None = None
price: float

@app.post("/items/")
def create_item(item: ItemCreate, db: Session = Depends(get_db)):

1. 將 Pydantic 模型轉為 SQLAlchemy 模型

db_item = models.Item(name=item.name, description=item.description, price=item.price)

2. 加入資料庫的 session

db.add(db_item)

3. 提交變更 (真實寫入資料庫)

db.commit()

4. 更新物件狀態 (例如取得資料庫自動生成的 id)

db.refresh(db_item)

return db_item
這四個步驟是 SQLAlchemy 新增資料的標準流程。現在你可以打開 Swagger UI 測試一下,送出請求後,資料就會真真實實地保存在你的 SQLite 資料庫檔案中了!


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言