Skip to content

Commit

Permalink
#148: Move duplicated code to its own function
Browse files Browse the repository at this point in the history
- This involves moving the distinct fields belonging to the entity that's going to be sent into entity_to_dict() (via recursion) to be moved to the base so it can be checked when that recursion call executes
  • Loading branch information
MRichards99 committed Sep 22, 2020
1 parent 4470944 commit f4b89db
Showing 1 changed file with 25 additions and 15 deletions.
40 changes: 25 additions & 15 deletions common/icat/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,24 +265,23 @@ def entity_to_dict(self, entity, includes, distinct_fields=None):
" cause an issue further on in the request"
)
if isinstance(target, Entity):
recurse_distinct_fields = distinct_fields.copy()

if key in recurse_distinct_fields.keys():
# TODO - Add a comment about moving target entity fields to base
recurse_distinct_fields["base"] = recurse_distinct_fields[key]

d[key] = self.entity_to_dict(target, includes_copy, recurse_distinct_fields)
distinct_fields_copy = self.prepare_distinct_fields_for_recursion(
key, distinct_fields
)
d[key] = self.entity_to_dict(
target, includes_copy, distinct_fields_copy
)

# Related fields with one-many relationships are stored as EntityLists
elif isinstance(target, EntityList):
d[key] = []
for e in target:
recurse_distinct_fields = distinct_fields.copy()
if key in recurse_distinct_fields.keys():
# TODO - Add a comment about moving target entity fields to base
recurse_distinct_fields["base"] = recurse_distinct_fields[key]

d[key].append(self.entity_to_dict(e, includes_copy, recurse_distinct_fields))
distinct_fields_copy = self.prepare_distinct_fields_for_recursion(
key, distinct_fields
)
d[key].append(
self.entity_to_dict(e, includes_copy, distinct_fields_copy)
)
# Add actual piece of data to the dictionary
else:
entity_data = None
Expand Down Expand Up @@ -315,8 +314,8 @@ def map_distinct_attributes_to_entity_names(self, distinct_fields):
for field in distinct_fields:
split_fields = field.split(".")
if len(split_fields) == 1:
# Conventional list assignment causes IndexError because -2 is out of range
# of a list with a single element
# Conventional list assignment causes IndexError because -2 is out of
# range of a list with a single element
split_fields.insert(-2, "base")

try:
Expand All @@ -328,6 +327,17 @@ def map_distinct_attributes_to_entity_names(self, distinct_fields):

return distinct_field_dict

def prepare_distinct_fields_for_recursion(self, entity_name, distinct_fields):
"""
TODO - Add docstring
"""

distinct_fields_copy = distinct_fields.copy()
if entity_name in distinct_fields_copy.keys():
distinct_fields_copy["base"] = distinct_fields_copy[entity_name]

return distinct_fields_copy


def get_python_icat_entity_name(client, database_table_name):
"""
Expand Down

0 comments on commit f4b89db

Please sign in to comment.