commit 16c7edf0d0c1ce0356f29c231cbef06685b2c7b0 Author: gitadmin Date: Wed Nov 18 16:25:00 2026 +0800 init: 示例工程 diff --git a/README.md b/README.md new file mode 100644 index 0000000..4642720 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# simple-python + +最小 Python 示例:`app.OrderService.create_order` → `utils.load_config`,带内存仓储实现。 + +运行:`python3 app.py` diff --git a/app.py b/app.py new file mode 100644 index 0000000..598db93 --- /dev/null +++ b/app.py @@ -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)) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..55b7ead --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +# 示例仓无第三方依赖,保持空清单 diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..3715ef3 --- /dev/null +++ b/utils.py @@ -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