Skip to content

Commit 8d5546e

Browse files
committed
Add BaseModel.from_file() and BaseModel.to_file() methods
1 parent 6bb734a commit 8d5546e

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

osc/util/models.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,29 @@ def dict(self):
462462

463463
return result
464464

465+
@classmethod
466+
def from_file(cls, path: str) -> "Self":
467+
"""
468+
Load model from a json file.
469+
"""
470+
import json
471+
472+
with open(path, "r", encoding="utf-8") as f:
473+
data = json.load(f)
474+
475+
obj = cls(**data)
476+
return obj
477+
478+
def to_file(self, path: str):
479+
"""
480+
Dump model to a json file.
481+
"""
482+
import json
483+
484+
with open(path, "w", encoding="utf-8") as f:
485+
# we prefer key ordering according to the fields in the model
486+
json.dump(self.dict(), f, sort_keys=False, indent=4)
487+
465488
def do_snapshot(self):
466489
"""
467490
Save ``self.dict()`` result as a new starting point for detecting changes in the object data.

0 commit comments

Comments
 (0)