Keep partial collection failures visible
Report a result for every requested host without treating missing exports as healthy systems.
A useful batch can contain failures
When a fleet export is incomplete, stopping at the first missing file hides the systems you could still assess. Catch expected per-host problems and return a result for each requested host. A missing file, malformed JSON and a structurally invalid snapshot are different outcomes with different recovery actions.
Keep the failure explicit. Returning an empty dictionary for every error makes it difficult for downstream code to distinguish a healthy but sparse snapshot from a failed collection. This function includes a status and sets data to None when no valid observation is available.
Validate names before constructing paths
A host identifier becomes part of a filename here. Accept only this exercise's documented ASCII letters, digits and hyphens after normalization. Reject the complete request if any identifier is invalid, before opening a snapshot. Inputs such as ../outside are not hostnames in this export format.
Deduplicate normalized hosts and sort them for predictable output. Check that the JSON object's host matches the requested host exactly; a valid JSON file can still belong to the wrong machine.
Do not catch every possible exception. Unexpected I/O failures should remain visible to the caller. This is a file collection exercise in the browser, not a simulation of successful remote connections or evidence that a live system is reachable.
import json
from pathlib import Path
print(json.loads(Path("snapshots/srv-01.json").read_text(encoding="utf-8"))["host"])
Put it into practice.
Define collect_snapshots(root, hosts). Normalize identifiers with strip().casefold(); require regex [a-z0-9][a-z0-9-]* and reject any invalid host with ValueError before reading. Visit unique hosts in sorted order, reading root/<host>.json. Return host,status,data for each: ok plus the original object if its host exactly matches; missing plus None for FileNotFoundError; invalid JSON plus None for decoding/JSON errors; invalid snapshot plus None for a non-object or wrong host. Continue after these expected failures; propagate other I/O errors.
See an explained solution
import json, re
from pathlib import Path
def collect_snapshots(root, hosts):
normalized = []
for host in hosts:
if not isinstance(host, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]*", host.strip().casefold()):
raise ValueError("Invalid host identifier")
normalized.append(host.strip().casefold())
results = []
for host in sorted(set(normalized)):
try:
data = json.loads((Path(root) / (host + ".json")).read_text(encoding="utf-8"))
except FileNotFoundError:
status, data = "missing", None
except (ValueError, UnicodeError):
status, data = "invalid JSON", None
else:
if not isinstance(data, dict) or data.get("host") != host:
status, data = "invalid snapshot", None
else:
status = "ok"
results.append({"host": host, "status": status, "data": data})
return results
if __name__ == "__main__":
print(collect_snapshots("snapshots", ["srv-01", "srv-02"]))
Every requested host receives an explicit result, so later reports can count unavailable evidence. Identity validation prevents an accidentally misnamed file being attributed to another system.