Skip to content

Commit

Permalink
Trust the deserialized values
Browse files Browse the repository at this point in the history
Change the (de)serialization logic, so the serialization expects that
the object is valid. All default values and validation happens now upon
deserialization. That concentrates the logic into a single place.
  • Loading branch information
Glutexo committed Jul 3, 2019
1 parent b0a78ae commit be58344
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions app/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import uuid

from collections import defaultdict
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from marshmallow import Schema, fields, validate, validates, ValidationError
Expand Down Expand Up @@ -90,7 +91,7 @@ def from_json(cls, data):
data.get("ansible_host"),
data.get("account"),
Facts.from_json(data.get("facts")),
data.get("system_profile", {}),
data.get("system_profile")
)

def to_json(self):
Expand All @@ -108,7 +109,7 @@ def to_json(self):
def to_system_profile_json(self):
return {
"id": _serialize_uuid(self.id),
"system_profile": self.system_profile_facts or {}
"system_profile": self.system_profile_facts
}

def save(self):
Expand Down Expand Up @@ -247,13 +248,12 @@ class Facts:

@classmethod
def from_json(cls, data):
facts = {}
facts = defaultdict(lambda: {})
for item in data or []:
try:
if item["namespace"] in facts:
facts[item["namespace"]].update(item["facts"])
else:
facts[item["namespace"]] = item["facts"]
old_facts = facts[item["namespace"]]
new_facts = item["facts"] or {}
facts[item["namespace"]] = {**old_facts, **new_facts}
except KeyError:
# The facts from the request are formatted incorrectly
raise InputFormatException("Invalid format of Fact object. Fact "
Expand All @@ -263,7 +263,7 @@ def from_json(cls, data):
@classmethod
def to_json(cls, facts):
return [
{"namespace": namespace, "facts": facts or {}}
{"namespace": namespace, "facts": facts}
for namespace, facts in facts.items()
]

Expand Down

0 comments on commit be58344

Please sign in to comment.