Metadata-Version: 2.4
Name: autocrud
Version: 0.7.2
Summary: 自動產生 CRUD API 的 Python 函式庫
Project-URL: Homepage, https://github.com/HYChou0515/autocrud
Project-URL: Documentation, https://HYChou0515.github.io/autocrud/
Project-URL: Repository, https://github.com/HYChou0515/autocrud.git
Project-URL: Issues, https://github.com/HYChou0515/autocrud/issues
Author-email: HYChou0515 <hychou.svm@example.com>
License: MIT License
        
        Copyright (c) 2025 HYChou0515
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: api,automation,crud,fastapi,rest
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Requires-Dist: fastapi>=0.116.1
Requires-Dist: jsonpatch>=1.33
Requires-Dist: jsonpointer>=3.0.0
Requires-Dist: more-itertools>=10.7.0
Requires-Dist: msgpack>=1.1.1
Requires-Dist: msgspec>=0.19.0
Requires-Dist: pydantic>=2.11.7
Requires-Dist: qqabc>=0.2.1
Requires-Dist: strawberry-graphql>=0.288.1
Requires-Dist: xxhash>=3.5.0
Provides-Extra: cli
Requires-Dist: datamodel-code-generator[http]>=0.35.0; extra == 'cli'
Requires-Dist: fstui>=0.1.1; extra == 'cli'
Requires-Dist: httpx>=0.28.1; extra == 'cli'
Requires-Dist: tenacity>=9.1.2; extra == 'cli'
Requires-Dist: textual>=6.3.0; extra == 'cli'
Requires-Dist: typer>=0.20.0; extra == 'cli'
Provides-Extra: dev
Requires-Dist: boto3>=1.40.21; extra == 'dev'
Requires-Dist: coverage>=7.9.2; extra == 'dev'
Requires-Dist: furo>=2025.7.19; extra == 'dev'
Requires-Dist: linkify-it-py>=2.0.3; extra == 'dev'
Requires-Dist: myst-parser>=4.0.1; extra == 'dev'
Requires-Dist: pytest-asyncio>=1.1.0; extra == 'dev'
Requires-Dist: pytest>=8.4.1; extra == 'dev'
Requires-Dist: python-magic>=0.4.27; extra == 'dev'
Requires-Dist: ruff>=0.12.4; extra == 'dev'
Requires-Dist: sphinx-autodoc-typehints>=3.2.0; extra == 'dev'
Requires-Dist: sphinx-design>=0.6.1; extra == 'dev'
Requires-Dist: sphinx-termynal>=0.2.1; extra == 'dev'
Requires-Dist: sphinx>=8.2.3; extra == 'dev'
Requires-Dist: sphinxcontrib-mermaid>=1.2.3; extra == 'dev'
Provides-Extra: docs
Requires-Dist: boto3>=1.40.21; extra == 'docs'
Requires-Dist: furo>=2025.7.19; extra == 'docs'
Requires-Dist: linkify-it-py>=2.0.3; extra == 'docs'
Requires-Dist: myst-parser>=4.0.1; extra == 'docs'
Requires-Dist: sphinx-autodoc-typehints>=3.2.0; extra == 'docs'
Requires-Dist: sphinx-design>=0.6.1; extra == 'docs'
Requires-Dist: sphinx-termynal>=0.2.1; extra == 'docs'
Requires-Dist: sphinx>=8.2.3; extra == 'docs'
Requires-Dist: sphinxcontrib-mermaid>=1.2.3; extra == 'docs'
Provides-Extra: magic
Requires-Dist: python-magic>=0.4.27; extra == 'magic'
Provides-Extra: mq
Requires-Dist: pika>=1.3.2; extra == 'mq'
Provides-Extra: s3
Requires-Dist: boto3>=1.40.21; extra == 's3'
Description-Content-Type: text/markdown

# AutoCRUD

[![Docs](https://img.shields.io/badge/Docs-Documentation-blue)](https://hychou0515.github.io/autocrud/)
[![PyPI](https://img.shields.io/pypi/v/autocrud)](https://pypi.org/project/autocrud/)
[![FastAPI](https://img.shields.io/badge/FastAPI-Automation-009688)](https://fastapi.tiangolo.com)
[![GraphQL](https://img.shields.io/badge/GraphQL-Supported-E10098?logo=graphql)](https://graphql.org/)
[![msgspec](https://img.shields.io/badge/msgspec-Supported-5e60ce)](https://github.com/jcrist/msgspec)
[![Versioning](https://img.shields.io/badge/Versioning-Built--in-blue)]()

<div style="padding:12px;border:1px solid #add3ff99;border-radius:8px;background: #add3ff33;">
  <strong>AutoCRUD 是模型驅動的自動化FastAPI：</strong>內建版本控制、權限與搜尋，聚焦業務邏輯快速上線。
</div>

## ✨ 特色

- 🧠 **只需關心業務與模型**：開發者只需專注 business logic 與 domain model schema；metadata、索引、事件、權限等基礎能力由框架自動處理
- ⚙️ **自動 FastAPI**：一行代碼套用模型，自動生成 CRUD 路由與 OpenAPI/Swagger，零樣板、零手工綁定
- 🗂️ **版本控制**：原生支援完整版本歷史、草稿不進版編輯、版本切換與還原，適合審計/回溯/草稿流程
- 🔧 **高度可定制**：靈活的路由命名、索引欄位、事件處理器與權限檢查
- 🏎️ **高性能**：基於 FastAPI + msgspec，低延遲高吞吐

## 功能概覽

| 功能 | 說明 |
| :--- | :--- |
| ✅ 自動生成 (Schema → API/Storage) | `Schema as Infrastructure`：自動產生路由、邏輯綁定與儲存映射 |
| ✅ 版本控制 (Revision History) | Draft→Update / Stable→Append、完整 parent revision 鏈 |
| ✅ 遷移 (Migration) | Functional Converter，Lazy Upgrade on Read + Save |
| ✅ 儲存架構 (Storage) | Hybrid：Meta (SQL/Redis) + Payload (Object Store) + Blob |
| ✅ 可擴展性 (Scale Out) | 使用 Object Storage 與索引分離，便於水平擴展 |
| ✅ 局部更新 (Partial Update / PATCH) | JSON Patch精準更新, 提速省頻寬 |
| ✅ 局部讀取 (Partial Read) | msgspec 解碼階段跳過不必要欄位, 提速省頻寬 |
| ✅ GraphQL 整合 | 自動產生 Strawberry GraphQL Endpoint |
| ✅ Blob優化 | BlobStore 去重、延遲載入 |
| ✅ 權限控制 (Permissions) | Global / Model / Resource 三層 RBAC 與自定義檢查器 |
| ✅ Event Hooks | 每種操作都可以自訂 Before / After / OnSuccess / OnError |
| ✅ Route Templates | 標準 CRUD 與plug-in自定義端點 |
| ✅ 搜尋與索引 (Search / Index) | Meta Store 提供高效篩選、排序、分頁與複雜查詢 |
| ✅ 審計 / 日誌 (Audit / Logging) | 支援事件後的審計紀錄與審查流程 |
| ✅ 訊息佇列 (Message Queue) | 內建非同步任務處理，將 Job 視為資源進行版本與狀態管理 |

## 安裝

```
pip install autocrud
```

**Optional Dependencies**

若需要 **S3** 儲存支援：

```
pip install "autocrud[s3]"
```

若需要 **BlobStore 自動偵測 Content-Type**：

```
pip install "autocrud[magic]"
```

`autocrud[magic]` 依賴 `python-magic`。
- **Linux**: 需確認環境已安裝 `libmagic` (例如 Ubuntu 下執行 `sudo apt-get install libmagic1`)。
- **其他 OS**: 請參考 [python-magic 安裝說明](https://github.com/ahupp/python-magic#installation)。

## 文檔

https://hychou0515.github.io/autocrud/


## 第一個 API

```python
from datetime import datetime, timedelta
from fastapi import FastAPI
from fastapi.testclient import TestClient
from autocrud import AutoCRUD
from msgspec import Struct

class TodoItem(Struct):
    title: str
    completed: bool
    due: datetime

class TodoList(Struct):
    items: list[TodoItem]
    notes: str

# 創建 AutoCRUD
crud = AutoCRUD()
crud.add_model(TodoItem)
crud.add_model(TodoList)

app = FastAPI()
crud.apply(app)
crud.openapi(app)

uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
```
## 自動生成的CRUD端點

- `POST /todo-item` - 創建
- `GET /todo-item/{id}/data` - 讀取
- `PATCH /todo-item/{id}` - JSON Patch 更新
- `DELETE /todo-item/{id}` - 軟刪除
- `GET /todo-list/data` - 列表, 支援搜尋
- *其他十多種auto endpoints*

➡️ *[AutoCRUD 使用指南](https://hychou0515.github.io/autocrud/auto_routes)*

## 透過 ResourceManager 操作資源

ResourceManager 是 AutoCRUD 的資源操作入口，負責管理資源的建立、查詢、更新、刪除、版本等操作。

其核心是「版本控制」：每次 `create/update/patch` 都會產生新的 `revision_id`（進版），完整保留歷史；草稿（`draft`）可用 `modify` 不進版反覆編輯，確認後切換為 `stable`。你也可以列出所有版本、讀取任意版本、`switch` 切換目前版本，或在軟刪除後 `restore` 還原。索引查詢支援依 metadata 與資料欄位（indexed fields）進行篩選、排序與分頁，適合審計、回溯與大量資料的檢索。

➡️ *[ResourceManager 使用說明](https://hychou0515.github.io/autocrud/resource_manager)*


## 🚀 快速開始


```python
from datetime import datetime, timedelta
from fastapi import FastAPI
from fastapi.testclient import TestClient
from autocrud import AutoCRUD
from msgspec import Struct

class TodoItem(Struct):
    title: str
    completed: bool
    due: datetime

class TodoList(Struct):
    items: list[TodoItem]
    notes: str

# 創建 CRUD API
crud = AutoCRUD()
crud.add_model(TodoItem)
crud.add_model(TodoList)

app = FastAPI()
crud.apply(app)

# 測試
client = TestClient(app)
resp = client.post("/todo-list", json={"items": [], "notes": "我的待辦"})
todo_id = resp.json()["resource_id"]

# 使用 JSON Patch 添加項目
client.patch(f"/todo-list/{todo_id}", json=[{
    "op": "add", 
    "path": "/items/-",
    "value": {
        "title": "完成項目",
        "completed": False,
        "due": (datetime.now() + timedelta(hours=1)).isoformat()
    }
}])

# 獲取結果
result = client.get(f"/todo-list/{todo_id}/data")
print(result.json())
```

**啟動開發服務器:**

```bash
python -m fastapi dev main.py
```

訪問 http://localhost:8000/docs 查看自動生成的 API 文檔。
