# entity_import.dspy —— 实体文件导入(REST /api/*) # 入参:world_id / scene_id / file_name / file(文件内容,FileStorage 或文本) # 事务批量:全量校验 → 整批插入;任一条失败回滚无脏数据。 # 返回 {success, total, success_count, fail, file_name} try: content = None fname = (params_kw.get('file_name') or '').strip() file_obj = params_kw.get('file') if file_obj is not None: if hasattr(file_obj, 'read'): content = file_obj.read() else: content = file_obj if content is None: content = params_kw.get('content') if content is None and not fname: raise EntityError('PARAM_REQUIRED', '缺少导入文件', 'file') if not fname: fname = (getattr(file_obj, 'filename', '') or '') if file_obj is not None else '' parsed = await parse_entity_file(content, fname) rows = parsed.get('rows', []) imp_ns = { 'world_id': params_kw.get('world_id'), 'scene_id': params_kw.get('scene_id'), 'file_name': fname or 'entity_import', 'rows': rows, } result = await import_entities(imp_ns) result['success'] = True return {'code': 'OK', 'message': 'success', 'data': result} except Exception as e: if hasattr(e, 'to_dict'): err = e.to_dict() return {'code': err['code'], 'message': err['message'], 'field': err['field'], 'detail': err['detail']} return {'code': 'DB_ERROR', 'message': '导入失败', 'field': '', 'detail': str(e)}