Skip to content

Commit

Permalink
Merge branch 'missing-drop' of github.com:jayd3e/colander into jayd3e…
Browse files Browse the repository at this point in the history
…-missing-drop
  • Loading branch information
mcdonc committed Mar 20, 2013
2 parents 981cb38 + a564f43 commit 5b9c9ff
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
18 changes: 16 additions & 2 deletions colander/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ def __reduce__(self):

null = _null()

class _drop(object):
"""
Represents a value that should be dropped if it is missing during
deserialization.
"""
pass

drop = _drop()

def interpolate(msgs):
for s in msgs:
if hasattr(s, 'interpolate'):
Expand Down Expand Up @@ -532,11 +541,14 @@ def _impl(self, node, value, callback):
name = subnode.name
subval = value.pop(name, null)
try:
result[name] = callback(subnode, subval)
sub_result = callback(subnode, subval)
except Invalid as e:
if error is None:
error = Invalid(node)
error.add(e, num)
else:
if sub_result is not drop:
result[name] = sub_result

if self.unknown == 'raise':
if value:
Expand Down Expand Up @@ -1641,7 +1653,9 @@ class _SchemaNode(object):
not provided, the missing value of this node will be the special marker
value :attr:`colander.required`, indicating that it is considered
'required'. When ``missing`` is :attr:`colander.required`, the
``required`` computed attribute will be ``True``.
``required`` computed attribute will be ``True``. When ``missing`` is
:attr:`colander.drop`, the node is dropped from the schema if it isn't
set during serialization/deserialization.
- ``preparer``: Optional preparer for this node. It should be
an object that implements the
Expand Down
10 changes: 10 additions & 0 deletions colander/tests/test_colander.py
Original file line number Diff line number Diff line change
Expand Up @@ -2897,6 +2897,16 @@ class MySchema(colander.Schema):
self.assertEqual(node.children[2].title, '')
self.assertEqual(node.children[3].title, 'thing2')

def test_deserialize_drop(self):
import colander
class MySchema(colander.Schema):
a = colander.SchemaNode(colander.String())
b = colander.SchemaNode(colander.String(), missing=colander.drop)
node = MySchema()
expected = {'a': 'test'}
result = node.deserialize(expected)
self.assertEqual(result, expected)

class TestSequenceSchema(unittest.TestCase):
def test_succeed(self):
import colander
Expand Down
4 changes: 4 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,7 @@ Schema-Related
.. attribute:: required

Represents a required value in colander-related operations.

.. attribute:: drop
Represents a value that will be dropped from the schema if it is missing. Passed
ass a value to the `missing` keyword argument.

0 comments on commit 5b9c9ff

Please sign in to comment.