从上传的 JSON 文件导入快照并立即恢复仿真状态。 Content-Type: application/json → JSON 解析 同时接受 multipart/form-data 中的 ``file`` 字段(前端文件上传)。
()
| 1375 | @require_role('admin') |
| 1376 | @rate_limit(10, 60) |
| 1377 | def snapshot_import(): |
| 1378 | """从上传的 JSON 文件导入快照并立即恢复仿真状态。 |
| 1379 | |
| 1380 | Content-Type: application/json → JSON 解析 |
| 1381 | 同时接受 multipart/form-data 中的 ``file`` 字段(前端文件上传)。 |
| 1382 | """ |
| 1383 | content_type = request.content_type or "" |
| 1384 | |
| 1385 | if "multipart/form-data" in content_type: |
| 1386 | file = request.files.get("file") |
| 1387 | if file is None: |
| 1388 | return error_response("VALIDATION_ERROR", "multipart 请求中未找到 'file' 字段") |
| 1389 | raw_text = file.read(4 * 1024 * 1024).decode("utf-8", errors="replace") |
| 1390 | else: |
| 1391 | raw_bytes = request.get_data() |
| 1392 | raw_text = raw_bytes.decode("utf-8", errors="replace") |
| 1393 | |
| 1394 | if not raw_text.strip(): |
| 1395 | return error_response("VALIDATION_ERROR", "请求体为空") |
| 1396 | |
| 1397 | try: |
| 1398 | snap_data = _SnapshotManager.from_json(raw_text) |
| 1399 | except ValueError as ve: |
| 1400 | return error_response("VALIDATION_ERROR", f"快照解析失败: {ve}") |
| 1401 | |
| 1402 | errors = _SnapshotManager.validate(snap_data) |
| 1403 | if errors: |
| 1404 | return error_response("VALIDATION_ERROR", "; ".join(errors)) |
| 1405 | |
| 1406 | try: |
| 1407 | result = simulation_engine.restore(snap_data) |
| 1408 | except ValueError as ve: |
| 1409 | return error_response("VALIDATION_ERROR", str(ve)) |
| 1410 | except Exception: |
| 1411 | logger.exception("快照导入恢复失败") |
| 1412 | return error_response("INTERNAL_ERROR") |
| 1413 | |
| 1414 | global _saved_snapshot |
| 1415 | _saved_snapshot = snap_data |
| 1416 | return ok(result) |
| 1417 | |
| 1418 | |
| 1419 | # ========================================== |