init: 示例工程

This commit is contained in:
gitadmin 2026-11-18 16:25:00 +08:00
commit 16c7edf0d0
4 changed files with 57 additions and 0 deletions

5
README.md Normal file
View File

@ -0,0 +1,5 @@
# simple-python
最小 Python 示例:`app.OrderService.create_order` → `utils.load_config`,带内存仓储实现。
运行:`python3 app.py`

33
app.py Normal file
View File

@ -0,0 +1,33 @@
"""最小示例服务:把订单接口包成函数,供检索/图谱样例使用。"""
from utils import load_config
class OrderService:
def __init__(self, repo):
self.repo = repo
self.config = load_config()
def create_order(self, sku: str, quantity: int) -> dict:
if quantity <= 0:
raise ValueError("数量必须为正")
if quantity > self.config["max_quantity"]:
raise ValueError("超过单次上限")
order = {"id": f"ORD-{sku}-{quantity}", "sku": sku, "quantity": quantity}
self.repo.save(order)
return order
class MemoryRepo:
def __init__(self):
self._items = {}
def save(self, order: dict) -> None:
self._items[order["id"]] = order
def find(self, order_id: str):
return self._items.get(order_id)
if __name__ == "__main__":
service = OrderService(MemoryRepo())
print(service.create_order("SKU-001", 2))

1
requirements.txt Normal file
View File

@ -0,0 +1 @@
# 示例仓无第三方依赖,保持空清单

18
utils.py Normal file
View File

@ -0,0 +1,18 @@
"""配置与通用工具。"""
DEFAULT_CONFIG = {"max_quantity": 99, "currency": "CNY"}
def load_config(path: str = None) -> dict:
"""读配置;没有文件就返回默认值,保证示例零依赖可跑。"""
cfg = dict(DEFAULT_CONFIG)
if not path:
return cfg
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
cfg[k.strip()] = int(v) if v.strip().isdigit() else v.strip()
return cfg