Skip to content
This repository
Browse code

specify optional fields with "missing=drop"

  • Loading branch information...
commit 21f525959fcc7c47ba063c28c9e3355d89cb9ae1 1 parent ff6d8c2
Andrew Brookins authored February 20, 2013
14  colander/__init__.py
@@ -40,6 +40,15 @@ def __reduce__(self):
40 40
 
41 41
 null = _null()
42 42
 
  43
+class _drop(object):
  44
+    """
  45
+    Represents a value that should be dropped if it is missing during
  46
+    deserialization.
  47
+    """
  48
+    pass
  49
+
  50
+drop = _drop()
  51
+
43 52
 def interpolate(msgs):
44 53
     for s in msgs:
45 54
         if hasattr(s, 'interpolate'):
@@ -531,11 +540,14 @@ def _impl(self, node, value, callback):
531 540
             name = subnode.name
532 541
             subval = value.pop(name, null)
533 542
             try:
534  
-                result[name] = callback(subnode, subval)
  543
+                sub_result = callback(subnode, subval)
535 544
             except Invalid as e:
536 545
                 if error is None:
537 546
                     error = Invalid(node)
538 547
                 error.add(e, num)
  548
+            else:
  549
+                if sub_result is not drop:
  550
+                    result[name] = sub_result
539 551
 
540 552
         if self.unknown == 'raise':
541 553
             if value:
10  colander/tests/test_colander.py
@@ -2895,6 +2895,16 @@ class MySchema(colander.Schema):
2895 2895
         self.assertEqual(node.children[2].title, '')
2896 2896
         self.assertEqual(node.children[3].title, 'thing2')
2897 2897
 
  2898
+    def test_deserialize_drop(self):
  2899
+        import colander
  2900
+        class MySchema(colander.Schema):
  2901
+            a = colander.SchemaNode(colander.String())
  2902
+            b = colander.SchemaNode(colander.String(), missing=colander.drop)
  2903
+        node = MySchema()
  2904
+        expected = {'a': 'test'}
  2905
+        result = node.deserialize(expected)
  2906
+        self.assertEqual(result, expected)
  2907
+
2898 2908
 class TestSequenceSchema(unittest.TestCase):
2899 2909
     def test_succeed(self):
2900 2910
         import colander

0 notes on commit 21f5259

Please sign in to comment.
Something went wrong with that request. Please try again.