Created
March 24, 2020 22:32
-
-
Save skatesham/ec9913a983154e308beb0479efbadcc1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Mapper: | |
def convertValue(self, data, obj): | |
""" | |
Mapper from dict to class, covering it's chieldrens but the key on dict must be mapping the chield with . | |
Exemple: data = { | |
"x": 0, | |
"y": 1, | |
"chield.a": "Sham Vinicius", | |
"chield.b": "Fiorin", | |
"chield.layer.c": "xxx", | |
"chield.layer.d": "yyy", | |
} | |
:param data: dict mapped as above | |
:param obj: obj with all the fields mapped | |
:return: the input obj with all data inserted injected in it | |
""" | |
for key, value in data.items(): | |
keys = key.split(".") | |
self.__convertValue(obj, keys, value) | |
return obj | |
def __convertValue(self, obj, keys, value): | |
""" | |
Recursive function for set data in the right field | |
:param obj: object or chield | |
:param keys: the keys in the key splited by '.' | |
:param value: value | |
:return: void | |
""" | |
if len(keys) == 1: | |
if not value: | |
value = "" | |
elif isinstance(value, Decimal): | |
value = str(value) | |
setattr(obj, keys[0], value) | |
return | |
obj = getattr(obj, keys[0]) | |
return self.__convertValue(obj, keys[1:], value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment