Skip to content
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

Feature: Task.to_dict #216

Merged
merged 1 commit into from
May 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion karton/core/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "5.1.0"
__version__ = "5.2.0"
54 changes: 33 additions & 21 deletions karton/core/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,38 @@ def merge_persistent_payload(self, other_task: "Task") -> None:
# Delete conflicting non-persistent payload
del self.payload[name]

def to_dict(self) -> Dict[str, Any]:
"""
Transform task data into dictionary
:return: Task data dictionary

:meta private:
"""

def serialize_resources(obj):
if type(obj) is dict:
return {k: serialize_resources(v) for k, v in obj.items()}
elif type(obj) is list or type(obj) is tuple:
return [serialize_resources(v) for v in obj]
elif isinstance(obj, ResourceBase):
return {"__karton_resource__": obj.to_dict()}
else:
return obj

return {
"uid": self.uid,
"root_uid": self.root_uid,
"parent_uid": self.parent_uid,
"orig_uid": self.orig_uid,
"status": self.status.value,
"priority": self.priority.value,
"last_update": self.last_update,
"payload": serialize_resources(self.payload),
"payload_persistent": serialize_resources(self.payload_persistent),
"headers": self.headers,
"error": self.error,
}

def serialize(self, indent: Optional[int] = None) -> str:
"""
Serialize task data into JSON string
Expand All @@ -235,28 +267,8 @@ def serialize(self, indent: Optional[int] = None) -> str:

:meta private:
"""

class KartonResourceEncoder(json.JSONEncoder):
def default(kself, obj: Any):
if isinstance(obj, ResourceBase):
return {"__karton_resource__": obj.to_dict()}
return json.JSONEncoder.default(kself, obj)

return json.dumps(
{
"uid": self.uid,
"root_uid": self.root_uid,
"parent_uid": self.parent_uid,
"orig_uid": self.orig_uid,
"status": self.status.value,
"priority": self.priority.value,
"last_update": self.last_update,
"payload": self.payload,
"payload_persistent": self.payload_persistent,
"headers": self.headers,
"error": self.error,
},
cls=KartonResourceEncoder,
self.to_dict(),
indent=indent,
sort_keys=True,
)
Expand Down