Skip to main content

AutoCRUD

🚀 自動生成 CRUD API 的 Python 庫 - 支持多種數據類型,零配置快速構建 REST API

Python FastAPI License

0.4.8 — 0.4.x 只剩一個用途:把資料搬到 specstar AutoCRUD.dump() 在 0.4.0–0.4.5 一呼叫就 TypeError;0.4.6 修好並改成直接輸出 specstar 的 .acbak 備份格式; 0.4.7 讓它遇到壞掉的 resource / revision 時跳過並回報,不再整個中斷,並會記錄進度; 0.4.8 讓它可以對線上正在跑的服務直接匯出(不再拿著 SQLite 游標讀檔而把寫入卡住):

import logging; logging.basicConfig(level=logging.INFO)   # 看進度
with open("backup.acbak", "wb") as f:
    report = crud.dump(f)      # {model: DumpReport(resources, revisions, bytes, seconds, skipped=[...])}
# 之後在 specstar 上:spec.load(open("backup.acbak", "rb"))

完整步驟見 Upgrading from autocrud 0.4.x

✨ 特色功能

  • 🎯 多數據類型支持: TypedDict、dataclass、msgspec.Struct
  • 零配置: 一行代碼生成完整 CRUD API
  • 🔧 高度可定制: 靈活的路由模板和命名約定
  • 📚 自動文檔: 集成 Swagger/OpenAPI 文檔
  • 🏎️ 高性能: 基於 FastAPI 和 msgspec
  • 🔒 類型安全: 完整的 TypeScript 風格類型檢查

🚀 快速開始

安裝

pip install autocrud
# 或使用 uv
uv add autocrud

5 分鐘創建 API

from msgspec import Struct
from fastapi import FastAPI, APIRouter
from autocrud.crud.core import (
    AutoCRUD, CreateRouteTemplate, ReadRouteTemplate,
    UpdateRouteTemplate, DeleteRouteTemplate, ListRouteTemplate
)

# 定義數據模型
class User(Struct):
    name: str
    email: str
    age: int = 0

# 創建 AutoCRUD 實例
crud = AutoCRUD(model_naming="kebab")

# 添加 CRUD 操作
crud.add_route_template(CreateRouteTemplate())
crud.add_route_template(ReadRouteTemplate())
crud.add_route_template(UpdateRouteTemplate())
crud.add_route_template(DeleteRouteTemplate())
crud.add_route_template(ListRouteTemplate())

# 註冊模型 - 就這麼簡單!
crud.add_model(User)

# 集成到 FastAPI
app = FastAPI(title="User API")
router = APIRouter()
crud.apply(router)
app.include_router(router)

# 運行: uvicorn main:app --reload

🎉 完成! 現在你有了一個完整的 CRUD API:

  • POST /user - 創建用戶
  • GET /user/{id} - 獲取用戶
  • PUT /user/{id} - 更新用戶
  • DELETE /user/{id} - 刪除用戶
  • GET /user - 列出所有用戶

📊 多數據類型支持

AutoCRUD 支持 Python 主流數據類型,你可以選擇最適合的:

from typing import TypedDict, Optional
from dataclasses import dataclass
import msgspec

# 1. TypedDict - 輕量級
class Product(TypedDict):
    name: str
    price: float
    in_stock: bool

# 2. msgspec.Struct - 高性能
class User(msgspec.Struct):
    username: str
    email: str
    age: Optional[int] = 0

# 3. dataclass - 原生支持
@dataclass
class Order:
    customer_id: str
    items: list
    total: float = 0.0

# 4. msgspec - 靈活數據
class Event(msgspec.Struct):
    type: str
    data: dict
    timestamp: float

# 一次註冊所有類型
crud.add_model(Product)   # /product
crud.add_model(User)      # /user  
crud.add_model(Order)     # /order
crud.add_model(Event)     # /event

🎯 實際示例

博客 API

from dataclasses import dataclass
from msgspec import Struct
from typing import List, Optional

class Author(Struct):
    name: str
    email: str
    bio: Optional[str] = ""

@dataclass
class BlogPost:
    title: str
    content: str
    author_id: str
    tags: List[str] = None
    published: bool = False

# 創建完整博客 API
crud = AutoCRUD(model_naming="kebab")
# ... 添加路由模板
crud.add_model(Author)    # /author
crud.add_model(BlogPost)  # /blog-post

電商系統

from decimal import Decimal
from enum import Enum
from msgspec import Struct

class OrderStatus(str, Enum):
    PENDING = "pending"
    SHIPPED = "shipped"
    DELIVERED = "delivered"

class Product(Struct):
    name: str
    price: Decimal
    stock: int
    category: str

class Order(Struct):
    customer_id: str
    items: List[dict]
    status: OrderStatus = OrderStatus.PENDING
    total: Decimal

# 完整電商 CRUD
crud.add_model(Product)  # /product
crud.add_model(Order)    # /order

⚙️ 配置選項

命名約定

# kebab-case (推薦)
crud = AutoCRUD(model_naming="kebab")
# UserProfile -> /user-profile

# snake_case
crud = AutoCRUD(model_naming="snake") 
# UserProfile -> /user_profile

# 自定義
def custom_naming(model_type):
    return f"api_{model_type.__name__.lower()}"
crud = AutoCRUD(model_naming=custom_naming)

選擇性 CRUD 操作

# 只讀 API
crud.add_route_template(ReadRouteTemplate())
crud.add_route_template(ListRouteTemplate())

# 基本 CRUD
crud.add_route_template(CreateRouteTemplate())
crud.add_route_template(ReadRouteTemplate()) 
crud.add_route_template(UpdateRouteTemplate())
crud.add_route_template(DeleteRouteTemplate())

# 高級功能
crud.add_route_template(PatchRouteTemplate())        # 部分更新
crud.add_route_template(SwitchRevisionRouteTemplate()) # 版本控制
crud.add_route_template(RestoreRouteTemplate())       # 恢復刪除

📖 文檔

🏃‍♂️ 運行示例

克隆倉庫並運行示例:

git clone https://github.com/HYChou0515/autocrud.git
cd autocrud

# 博客 API 示例
python examples/blog_api_example.py

# 電商 API 示例  
python examples/ecommerce_api_example.py

# 多數據類型示例
python examples/simple_quickstart.py

然後訪問 http://localhost:8000/docs 查看 API 文檔。

🧪 測試

# 安裝依賴
uv install

# 運行測試
uv run pytest

# 運行特定測試
uv run pytest tests/test_multiple_data_types.py -v

🤝 貢獻

歡迎貢獻!請查看 貢獻指南

📄 許可證

MIT License - 詳見 LICENSE 文件。

🌟 為什麼選擇 AutoCRUD?

傳統方式 😫

# 需要手寫大量樣板代碼
@app.post("/users")
async def create_user(user: UserCreate):
    # 驗證邏輯
    # 業務邏輯  
    # 數據庫操作
    # 錯誤處理
    # 響應格式化
    pass

@app.get("/users/{user_id}")
async def get_user(user_id: str):
    # 更多樣板代碼...
    pass

# ... 重複 5+ 個端點

AutoCRUD 方式 😎

# 一行代碼,完整 CRUD API
crud.add_model(User)

節省 90% 的開發時間! 🎯

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

autocrud-0.4.8.tar.gz (247.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

autocrud-0.4.8-py3-none-any.whl (87.1 kB view details)

Uploaded Python 3

File details

Details for the file autocrud-0.4.8.tar.gz.

File metadata

  • Download URL: autocrud-0.4.8.tar.gz
  • Upload date:
  • Size: 247.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.3

File hashes

Hashes for autocrud-0.4.8.tar.gz
Algorithm Hash digest
SHA256 50a69b9e97cd7a6604e892a1ced088edf1413cb209ac8d401a75cff09c9b1bfe
MD5 485703afc08ab7813538eb71ce1da801
BLAKE2b-256 928fff031e8200b21086ad18a1a877acbac5ed2f9a0ba572e0548d5e47183653

See more details on using hashes here.

File details

Details for the file autocrud-0.4.8-py3-none-any.whl.

File metadata

  • Download URL: autocrud-0.4.8-py3-none-any.whl
  • Upload date:
  • Size: 87.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.3

File hashes

Hashes for autocrud-0.4.8-py3-none-any.whl
Algorithm Hash digest
SHA256 6109125374e83b6b5b8ed6e6f2dd9e9d71b8c90fbaf2df32add31145472e3023
MD5 9a7955d712177da01666457a6fdc6e8c
BLAKE2b-256 a88fb6b675884ef7bac108c143b404fb94cffaf2959bb3de3f881c7a06ddcd21

See more details on using hashes here.

Release history Release notifications | RSS feed

0.10.0

2 files

0.9.0

2 files

0.8.5

2 files

0.8.4

2 files

0.8.3

2 files

0.8.2

2 files

0.8.1

2 files

0.8.0

2 files

0.7.7

2 files

0.7.6

2 files

0.7.5

2 files

0.7.4

2 files

0.7.3

2 files

0.7.2

2 files

0.7.1

2 files

0.7.0

2 files

0.6.9

2 files

0.6.8

2 files

0.6.7

2 files

0.6.6

2 files

0.6.5

2 files

0.6.4

2 files

0.6.3

2 files

0.6.2

2 files

0.6.1

2 files

0.6.0

2 files

0.5.0

2 files

This release

0.4.8 This release

2 files

0.4.7

2 files

0.4.6

2 files

0.4.5

2 files

0.4.4

2 files

0.4.3

2 files

0.4.2

2 files

0.4.1

2 files

0.4.0

2 files

0.3.5

2 files

0.3.4

2 files

0.3.2

2 files

0.3.1

2 files

0.3.0

2 files

0.2.2

2 files

0.2.1

2 files

0.2.0

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page