Create persistence.py
Browse files
engine_03/flow/persistence.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Union
|
| 4 |
+
|
| 5 |
+
from .graph_models import FlowGraph, Node, Edge
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def load_flow(path: Union[str, Path]) -> FlowGraph:
|
| 9 |
+
path = Path(path)
|
| 10 |
+
if not path.exists():
|
| 11 |
+
raise FileNotFoundError(path)
|
| 12 |
+
|
| 13 |
+
data = json.load(path.open("r", encoding="utf-8"))
|
| 14 |
+
nodes = [Node(**n) for n in data.get("nodes", [])]
|
| 15 |
+
edges = [Edge(**e) for e in data.get("edges", [])]
|
| 16 |
+
return FlowGraph(nodes=nodes, edges=edges)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def save_flow(flow: FlowGraph, path: Union[str, Path]) -> None:
|
| 20 |
+
path = Path(path)
|
| 21 |
+
data = {
|
| 22 |
+
"nodes": [n.__dict__ for n in flow.nodes],
|
| 23 |
+
"edges": [e.__dict__ for e in flow.edges],
|
| 24 |
+
}
|
| 25 |
+
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
|