pythonpyramidcolander

Validate optional values with Colander


I'm using Colander to validate request parameters for a Pyramid web server. For example:

class MySchema(colander.MappingSchema):                                         
    first_name = colander.SchemaNode(colander.String())                               
    last_name = colander.SchemaNode(colander.String())                              

Here, first_name and last_name are required parameters. If I use missing='' then this would make them optional, but they would still be added to the deserializing as an empty string which isn't really useful if the user submits an empty string.

Best I can think of is missing=None and then check for None later.

Is there a way to mark a parameter as truly optional? Meaning, if they're not in the request, they shouldn't be in the deserialized result either.


Solution

  • I think you're looking for missing=colander.drop.
    From docs:

    colander.drop - Represents a value that will be dropped from the schema if it is missing during deserialization. Passed as a value to the missing keyword argument of SchemaNode.