简体   繁体   中英

Formencode Compound Validators Inside Schemas

I'm trying to do something that I think should be straightforward, but I'm running into problems getting it to work. Here's what I have right now, which works as expected.

some_schema = Schema(

   multiples = ForEach(UnicodeString(), convert_to_list=True),
   single = OneOf(['a', 'b'])

)

What I would like to do is apply a MaxLength validator on the multiple value field after it has been converted to a list of unicode strings. However, It doesn't seem to like any of my attempts with compound (eg, All, Pipe) or custom validators. In my mind, here is the most straightforward way to accomplish this.

some_schema = Schema(

   multiples = All(MaxLength(5), ForEach(UnicodeString(), convert_to_list=True)),
   single = OneOf(['a', 'b'])

)

Based on the documentation, the multiple value field should be converted to a list of unicode strings, then run through the MaxLength validator, failing if it is > 5 elements. The failure part works:

>>> some_schema.to_python({'single':'a', 'multiples': range(6)})
>>> Invalid: multiples: Enter a value less than 5 characters long

However, an example that seems like it should pass actually fails:

>>> some_schema.to_python({'single':'a', 'multiples': range(3)})
>>> Invalid: multiples: Please provide only one value

The formencode documentation, though generally very good, has been unable to shed light on the subject. Looking at the source code, this is a single value expected exception from the Schema class. I tried passing the accepts_iterator=True argument to the Schema, but that fails also.

How can I make sure a field in a schema is a list of unicode strings and has a length less than N?

Answered my own question - you have to supply the accepts_iterator keyword to the MaxLength validator.

some_schema = Schema(

   multiples = All(MaxLength(5, accepts_iterator=True), ForEach(UnicodeString(), convert_to_list=True)),
   single = OneOf(['a', 'b'])

)

Works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM