36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
"""把物料定义导入 MongoDB:uv run python -m scripts.seed_materials [物料定义目录]
|
||
|
||
默认读取 app/resources/materials,导入后需重启服务生效
|
||
"""
|
||
|
||
import asyncio
|
||
import sys
|
||
|
||
from pymongo import AsyncMongoClient
|
||
|
||
from app.config import settings
|
||
from app.resources.component import MATERIALS_DIR, load_material_definitions
|
||
from app.services.material_mongo import MongoMaterialRepository
|
||
|
||
|
||
async def main(directory: str) -> None:
|
||
if not settings.mongodb_uri:
|
||
raise SystemExit("未配置 MONGODB_URI")
|
||
# 先完整校验定义,校验失败不会改动数据库
|
||
catalog = load_material_definitions(directory)
|
||
client = AsyncMongoClient(settings.mongodb_uri, serverSelectionTimeoutMS=5000)
|
||
try:
|
||
await MongoMaterialRepository(client[settings.mongodb_db]).replace_all(catalog)
|
||
finally:
|
||
await client.close()
|
||
print(
|
||
f"已导入 {len(catalog.components)} 个物料、"
|
||
f"{len(catalog.field_groups)} 个共享字段分组,版本 {catalog.version}"
|
||
)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# Windows 控制台默认编码无法输出中文
|
||
sys.stdout.reconfigure(encoding="utf-8")
|
||
asyncio.run(main(sys.argv[1] if len(sys.argv) > 1 else str(MATERIALS_DIR)))
|