Files
watcher-visio/dashboard/serializers.py
Nikolay Tatarinov 656a6bfac4
Some checks failed
CI / ci (push) Has been cancelled
Refactor dashboard data serialization and mock context for improved clarity
- Introduced `serialize_audit_for_response` and `serialize_current_cluster_for_template` functions to handle JSON serialization of audit and cluster data, enhancing data consistency for API responses and template rendering.
- Updated `get_mock_context` in `mock_data.py` to utilize the new serialization functions, simplifying the mock data structure and improving readability.
- Refactored `collect_context` and `collect_audits` in `views.py` to leverage the new serialization methods, ensuring a cleaner and more maintainable codebase.
- Added unit tests for the new serialization functions to ensure correctness and reliability of data formatting.
2026-02-12 20:10:09 +03:00

33 lines
1.2 KiB
Python

"""Serialization helpers for dashboard context and API responses."""
import json
def _ensure_json_str(value):
"""Return value as JSON string; if already a string, return as-is."""
return value if isinstance(value, str) else json.dumps(value)
def serialize_audit_for_response(audit: dict) -> dict:
"""
Return a copy of the audit dict with migrations, host_labels, cpu_current,
and cpu_projected serialized as JSON strings (for template/API response).
"""
result = dict(audit)
result["migrations"] = _ensure_json_str(audit.get("migrations"))
result["host_labels"] = _ensure_json_str(audit.get("host_labels"))
result["cpu_current"] = _ensure_json_str(audit.get("cpu_current"))
result["cpu_projected"] = _ensure_json_str(audit.get("cpu_projected"))
return result
def serialize_current_cluster_for_template(current_cluster: dict) -> dict:
"""
Return current_cluster with host_labels and cpu_current as JSON strings
for template embedding (e.g. in index.html).
"""
return {
"host_labels": _ensure_json_str(current_cluster.get("host_labels")),
"cpu_current": _ensure_json_str(current_cluster.get("cpu_current")),
}