-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add to_json method for exporting Entry metadata to JSON #306
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,6 +18,7 @@ | |
from uuid import uuid4 | ||
import warnings | ||
from collections import defaultdict | ||
from decimal import Decimal | ||
|
||
from sqlalchemy import Column, ForeignKey, event | ||
from sqlalchemy import Integer, String, Boolean, DateTime | ||
|
@@ -399,10 +400,41 @@ def from_dict(cls, session: Session, data: dict) -> 'Entry': | |
|
||
return entry | ||
|
||
|
||
@classmethod | ||
def is_valid(cls, entry: 'Entry') -> bool: | ||
return isinstance(entry, Entry) and entry.id is not None | ||
|
||
|
||
def to_json(self, path: str) -> None: | ||
""" | ||
Exports the Entry metadata (from the to_dict method) to a serializable | ||
JSON. | ||
|
||
.. versionadded:: 0.9.1 | ||
|
||
Parameters | ||
---------- | ||
path : str | ||
Path to the file to write the JSON to. | ||
|
||
""" | ||
# custom encoder for datetime and Decimal data types | ||
class DictToSerializableJsonEncoder(json.JSONEncoder): | ||
def default(self, obj): | ||
if isinstance(obj, Decimal): | ||
return str(obj) | ||
if isinstance(obj, dt): | ||
return obj.isoformat() | ||
return super().default(obj) | ||
Comment on lines
+423
to
+429
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's define this in some kind of utility file, so that other models can use it as well. |
||
|
||
# get the dict | ||
entry_dict = self.to_dict() | ||
|
||
# write | ||
with open(path, 'w') as f: | ||
json.dump(entry_dict, f, indent=4, cls=DictToSerializableJsonEncoder) | ||
Comment on lines
+435
to
+436
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ah ok. Other option is to keep the writing to file out of meta catalog and implement the class directly into the tool, where it is used. What do you think? |
||
|
||
@property | ||
def checksum(self) -> str: | ||
""" | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it would make more sense to convert the Decimal to a float, right?