Skip to content

Commit

Permalink
Handle convertings lists into Masrhmallow List fields
Browse files Browse the repository at this point in the history
  • Loading branch information
Joel Collins committed Jan 20, 2020
1 parent cc777d9 commit 6964029
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions labthings/server/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from typing import Dict, List, Tuple, Union
from uuid import UUID

import logging
import inspect
import copy

Expand Down Expand Up @@ -69,6 +70,7 @@ def to_string(o):
def make_primative(value):
global DEFAULT_BUILTIN_CONVERSIONS, DEFAULT_TYPE_MAPPING

logging.debug(f"Converting {value} to primative type...")
value_typestrings = [x.__module__+"."+x.__name__ for x in inspect.getmro(type(value))]

for typestring in value_typestrings:
Expand All @@ -86,6 +88,12 @@ def make_primative(value):

def value_to_field(value):
global DEFAULT_TYPE_MAPPING

if isinstance(value, (List, Tuple)) or type(value) is type(Union):
# Get type of elements from the zeroth element.
# NOTE: This is definitely not ideal, but we can TODO later
element_field = value_to_field(value[0])
return fields.List(element_field, example=value)
if type(value) in DEFAULT_TYPE_MAPPING:
return DEFAULT_TYPE_MAPPING.get(type(value))(example=value)
else:
Expand All @@ -94,10 +102,11 @@ def value_to_field(value):

def data_dict_to_schema(data_dict):
working_dict = copy.deepcopy(data_dict)

working_dict = rapply(working_dict, make_primative)
working_dict = rapply(working_dict, value_to_field, apply_to_iterables=False)

working_dict = rapply(working_dict, value_to_field)
return Schema.from_dict(working_dict)
return working_dict

# TODO: Deserialiser with inverse defaults
# TODO: Option to switch to .npy serialisation/deserialisation (or look for a better common array format)
Expand All @@ -113,6 +122,8 @@ def data_dict_to_schema(data_dict):
"subval2": False
},
"val2": 5
"val3": [1, 2, 3, 4]
"val4": range(1, 5)
}
"""

0 comments on commit 6964029

Please sign in to comment.