From 0a9ec62e6540a70cd42e954929ac133456df8333 Mon Sep 17 00:00:00 2001 From: Benjamin Scharf Date: Tue, 25 May 2021 23:55:32 -0500 Subject: [PATCH] Resolve issue #304; retain previous behavior. --- flask_restx/fields.py | 7 ++++++- flask_restx/marshalling.py | 2 +- tests/test_marshalling.py | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/flask_restx/fields.py b/flask_restx/fields.py index 031fdd61..18e973a0 100644 --- a/flask_restx/fields.py +++ b/flask_restx/fields.py @@ -862,7 +862,12 @@ def output(self, key, obj, ordered=False): # we are using pop() so that we don't # loop over the whole object every time dropping the # complexity to O(n) - (objkey, val) = self._flat.pop() + if ordered: + # Get first element if respecting order + (objkey, val) = self._flat.pop(0) + else: + # Previous default retained + (objkey, val) = self._flat.pop() if ( objkey not in self._cache and objkey not in self.exclude diff --git a/flask_restx/marshalling.py b/flask_restx/marshalling.py index 1c1e9c7c..8e899f7f 100644 --- a/flask_restx/marshalling.py +++ b/flask_restx/marshalling.py @@ -76,7 +76,7 @@ def marshal(data, fields, envelope=None, skip_none=False, mask=None, ordered=Fal if keys: field.exclude |= set(keys) keys = [] - value = field.output(dkey, data) + value = field.output(dkey, data, ordered=ordered) if is_wildcard: def _append(k, v): diff --git a/tests/test_marshalling.py b/tests/test_marshalling.py index 41460345..b88eaef1 100644 --- a/tests/test_marshalling.py +++ b/tests/test_marshalling.py @@ -221,6 +221,21 @@ def test_marshal_nested(self): assert output == expected + def test_marshal_ordered(self): + model = OrderedDict( + [("foo", fields.Raw), ("baz", fields.Raw), ("bar", fields.Raw)] + ) + marshal_fields = { + "foo": 1, + "baz": 2, + "bar": 3 + } + expected_ordered = OrderedDict([("foo", 1), ("baz", 2), ("bar", 3)]) + ordered_output = marshal(marshal_fields, model, ordered=True) + assert ordered_output == expected_ordered + unordered_output = marshal(marshal_fields, model) + assert not isinstance(unordered_output, OrderedDict) + def test_marshal_nested_ordered(self): model = OrderedDict( [("foo", fields.Raw), ("fee", fields.Nested({"fye": fields.String,}))]