Skip to content

Commit 823f61e

Browse files
ziirishSteadBytes
authored andcommitted
fix: make Wildcard fields support Nested and List fields (fix #728) (#739)
1 parent f21c261 commit 823f61e

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

flask_restplus/fields.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,9 +281,11 @@ def format(self, value):
281281
def is_attr(val):
282282
return self.container.attribute and hasattr(val, self.container.attribute)
283283

284+
if value is None:
285+
return []
284286
return [
285287
self.container.output(idx,
286-
val if (isinstance(val, dict) or is_attr(val)) and not is_nested else value)
288+
val if (isinstance(val, dict) or is_attr(val)) and not is_nested else value)
287289
for idx, val in enumerate(value)
288290
]
289291

@@ -793,6 +795,8 @@ def output(self, key, obj, ordered=False):
793795
return self.container.format(self.default)
794796
return None
795797

798+
if isinstance(self.container, Nested):
799+
return marshal(value, self.container.nested, skip_none=self.container.skip_none, ordered=ordered)
796800
return self.container.format(value)
797801

798802
def schema(self):

tests/test_marshalling.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,37 @@ def test_marshal(self):
2929
assert not isinstance(output, OrderedDict)
3030
assert output == {'foo': 'bar'}
3131

32+
def test_marshal_wildcard_nested(self):
33+
nest = fields.Nested(OrderedDict([('thumbnail', fields.String), ('video', fields.String)]))
34+
wild = fields.Wildcard(nest)
35+
wildcard_fields = OrderedDict([('*', wild)])
36+
model = OrderedDict([('preview', fields.Nested(wildcard_fields))])
37+
sub_dict = OrderedDict([
38+
('9:16', {'thumbnail': 24, 'video': 12}),
39+
('16:9', {'thumbnail': 25, 'video': 11}),
40+
('1:1', {'thumbnail': 26, 'video': 10})
41+
])
42+
marshal_dict = OrderedDict([('preview', sub_dict)])
43+
output = marshal(marshal_dict, model)
44+
assert output == {'preview': {'1:1': {'thumbnail': '26', 'video': '10'},
45+
'16:9': {'thumbnail': '25', 'video': '11'},
46+
'9:16': {'thumbnail': '24', 'video': '12'}}}
47+
48+
def test_marshal_wildcard_list(self):
49+
wild = fields.Wildcard(fields.List(fields.String))
50+
wildcard_fields = OrderedDict([('*', wild)])
51+
model = OrderedDict([('preview', fields.Nested(wildcard_fields))])
52+
sub_dict = OrderedDict([
53+
('1:1', [1, 2, 3]),
54+
('16:9', [4, 5, 6]),
55+
('9:16', [7, 8, 9])
56+
])
57+
marshal_dict = OrderedDict([('preview', sub_dict)])
58+
output = marshal(marshal_dict, model)
59+
assert output == {'preview': {'9:16': ['7', '8', '9'],
60+
'16:9': ['4', '5', '6'],
61+
'1:1': ['1', '2', '3']}}
62+
3263
def test_marshal_with_envelope(self):
3364
model = OrderedDict([('foo', fields.Raw)])
3465
marshal_dict = OrderedDict([('foo', 'bar'), ('bat', 'baz')])

0 commit comments

Comments
 (0)