forked from p15670423/monkey
Island: Change json encoding to encode Enums to name string
Enum objects couldn't get encoded, so for each enum we had to decide whether the name or the value would be used to represent that enum value. Changing the encoding to name allows us to use enum object on the island without having to worry about encoding.
This commit is contained in:
parent
c0f0d35f0b
commit
0474e2a5f7
|
@ -1,4 +1,5 @@
|
|||
from datetime import datetime
|
||||
from enum import Enum
|
||||
|
||||
import bson
|
||||
from bson.json_util import dumps
|
||||
|
@ -11,19 +12,27 @@ def normalize_obj(obj):
|
|||
del obj["_id"]
|
||||
|
||||
for key, value in list(obj.items()):
|
||||
if isinstance(value, bson.objectid.ObjectId):
|
||||
obj[key] = str(value)
|
||||
if isinstance(value, datetime):
|
||||
obj[key] = str(value)
|
||||
if isinstance(value, dict):
|
||||
obj[key] = normalize_obj(value)
|
||||
if isinstance(value, list):
|
||||
for i in range(0, len(value)):
|
||||
if isinstance(value[i], dict):
|
||||
value[i] = normalize_obj(value[i])
|
||||
obj[key][i] = _normalize_value(value[i])
|
||||
else:
|
||||
obj[key] = _normalize_value(value)
|
||||
return obj
|
||||
|
||||
|
||||
def _normalize_value(value):
|
||||
if type(value) == dict:
|
||||
return normalize_obj(value)
|
||||
if isinstance(value, bson.objectid.ObjectId):
|
||||
return str(value)
|
||||
if isinstance(value, datetime):
|
||||
return str(value)
|
||||
if issubclass(type(value), Enum):
|
||||
return value.name
|
||||
else:
|
||||
return value
|
||||
|
||||
|
||||
def output_json(obj, code, headers=None):
|
||||
obj = normalize_obj(obj)
|
||||
resp = make_response(dumps(obj), code)
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from unittest import TestCase
|
||||
|
||||
import bson
|
||||
|
@ -44,3 +45,11 @@ class TestRepresentations(TestCase):
|
|||
}
|
||||
),
|
||||
)
|
||||
|
||||
def test_normalize__enum(self):
|
||||
class BogusEnum(Enum):
|
||||
bogus_val = "Bogus"
|
||||
|
||||
my_obj = {"something": "something", "my_enum": BogusEnum.bogus_val}
|
||||
|
||||
assert {"something": "something", "my_enum": "bogus_val"} == normalize_obj(my_obj)
|
||||
|
|
Loading…
Reference in New Issue