Skip to content

Commit

Permalink
Try to fix dumping with data_key
Browse files Browse the repository at this point in the history
  • Loading branch information
jonls authored and gtmanfred committed Jun 3, 2022
1 parent f576895 commit 7983f88
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
7 changes: 5 additions & 2 deletions flask_rebar/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,24 @@ def filter_dump_only(schema, data):
"""
# Note as of marshmallow 3.13.0, Schema.dump_only is NOT populated if fields are declared as dump_only inline,
# so we'll calculate "dump_only" ourselves. ref: https://github.com/marshmallow-code/marshmallow/issues/1857
output_to_input_keys = {
field.data_key: key for key, field in schema.fields.items() if field.data_key
}
dump_only_fields = schema.dump_fields.keys() - schema.load_fields.keys()
if isinstance(data, Mapping):
dump_only = dict()
non_dump_only = dict()
# get our dump_only fields directly, and candidates for loadable:
for k, v in data.items():
if k in dump_only_fields:
if output_to_input_keys.get(k, k) in dump_only_fields:
dump_only[k] = v
else:
non_dump_only[k] = v

# construct loadable (a subset of non_dump_only, with recursive filter of nested dump_only fields)
loadable = dict()
for k, v in non_dump_only.items():
field = schema.fields[k]
field = schema.fields[output_to_input_keys.get(k, k)]
# see if we have a nested schema (using either Nested(many=True) or List(Nested())
field_schema = None
if isinstance(field, fields.Nested):
Expand Down
10 changes: 10 additions & 0 deletions tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,13 @@ def test_deserialize_errors(self):
self.assertEqual(
ctx.exception.messages, {"foos": {1: ["Not a valid integer."]}}
)


class DataKeySchema(RequireOnDumpMixin, Schema):
test_field = fields.String(data_key="testField")


class TestDataKey(TestCase):
def test_dump_and_validate_with_data_key(self):
result = compat.dump(DataKeySchema(), {"test_field": "abc"})
self.assertEqual(result, {"testField": "abc"})

0 comments on commit 7983f88

Please sign in to comment.