Skip to content
This repository has been archived by the owner on Feb 2, 2018. It is now read-only.

Commit

Permalink
models: to_json* now can expose internal attributes
Browse files Browse the repository at this point in the history
to_json/to_json_safe will replace Cluster.to_json_with_hosts and allow
any model to expose internal attributes.

Do:

    Cluster.to_json(expose=['hosts'])
    Cluster.to_json_safe(expose=['hosts'])

Instead of:

    Cluster.to_json_with_hosts()
    Cluster.to_json_with_hosts(secure=True)
  • Loading branch information
ashcrow authored and mbarnes committed Mar 8, 2017
1 parent 96dcbf0 commit e017998
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 17 deletions.
56 changes: 39 additions & 17 deletions src/commissaire/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,28 +168,38 @@ def _dict_for_json(self, secure):
data[key] = getattr(self, key)
return data

def to_json(self):
def to_json(self, expose=[]):
"""
Returns a JSON representation of this model.
:param expose: List of non exposed attributes to include in result.
:type expose: list
:returns: The JSON representation.
:rtype: str
"""
return json.dumps(
self._struct_for_json(secure=True),
default=lambda o: o._struct_for_json(secure=True))
struct = self._struct_for_json(secure=True)
for key in expose:
value = getattr(self, key)
if value:
struct[key] = value
return json.dumps(struct)

def to_json_safe(self):
def to_json_safe(self, expose=[]):
"""
Returns a JSON representation of this model, omitting all hidden
attributes. Use this when preparing data for display to users.
:param expose: List of non exposed attributes to include in result.
:type expose: list
:returns: The JSON representation.
:rtype: str
"""
return json.dumps(
self._struct_for_json(secure=False),
default=lambda o: o._struct_for_json(secure=False))
struct = self._struct_for_json(secure=False)
for key in expose:
value = getattr(self, key)
if value:
struct[key] = value
return json.dumps(struct)

def to_dict(self):
"""
Expand Down Expand Up @@ -348,22 +358,34 @@ class Cluster(Model):
_primary_key = 'name'

def __init__(self, **kwargs):
"""
Creates a new instance of Cluster.
:param kwargs: All keyword arguments to create the Cluster model.
:type kwargs: dict
:returns: The Cluster instance.
:rtype: commissaire.model.Cluster
"""
Model.__init__(self, **kwargs)
# Hosts is always calculated, not stored in etcd.
self.hosts = {'total': 0,
'available': 0,
'unavailable': 0}

# FIXME Generalize and move to Model?
# TODO: Remove in > 0.0.3
def to_json_with_hosts(self, secure=False):
data = {}
for key in list(self._attribute_map.keys()):
if secure:
data[key] = getattr(self, key)
elif key not in self._hidden_attributes:
data[key] = getattr(self, key)
data['hosts'] = self.hosts
return json.dumps(data)
"""
Returns a JSON representation of this model with host data.
.. deprecated:: 0.0.3
Use :func:`to_json` with the **expose** parameter instead.
:param secure: Include _hidden attributes in the return value.
:type secure: bool
:returns: The JSON representation.
:rtype: str
"""
return self.to_json(expose=['hosts'])

def to_dict_with_hosts(self, secure=False): # pragma: no cover
"""
Expand Down
18 changes: 18 additions & 0 deletions test/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,15 @@ def test_to_json(self):
'ssh_priv_key',
json.loads(instance.to_json()))

def test_to_json_with_expose(self):
"""
Verify to_json returns additional exposed items in the json string.
"""
instance = models.Cluster.new(name='test')
self.assertIn(
'hosts',
json.loads(instance.to_json(expose=['hosts'])))

def test_to_json_safe(self):
"""
Verify to_json_safe returns a sanitized json string.
Expand All @@ -61,6 +70,15 @@ def test_to_json_safe(self):
'ssh_priv_key',
json.loads(instance.to_json_safe()))

def test_to_json_safe_with_expose(self):
"""
Verify to_json_safe returns additional exposed items in the json string.
"""
instance = models.Cluster.new(name='test')
self.assertIn(
'hosts',
json.loads(instance.to_json_safe(expose=['hosts'])))

def test_to_dict(self):
"""
Verify to_dict returns a complete dict.
Expand Down

0 comments on commit e017998

Please sign in to comment.