Required and optional parameters in template?
dsalaza4 opened this issue · 4 comments
dsalaza4 commented
Does Confuse support required and optional parameters for template validation?
Something like:
confuse.Template({
'url': confuse.String(required=True),
'url2': confuse.OneOf(['a','b', 'c'], required=False)
}),
Expected results should be:
Pass:
url: abc
url: abc
url2: c
Fail:
url2: a
url: 2
url2: b
url: abc
url2: j
sampsyo commented
Yes! Most templates have a default
parameter, which, if set, means that they are optional.
Line 42 in 6ffb622
dsalaza4 commented
I tried with:
confuse.Template({
'url': confuse.String(default=REQUIRED),
'url2': confuse.OneOf(['a','b', 'c'])
}),
But it did not do the trick, I got no error due to a missing required key (url) :(
Also, is it possible to make an entire section required? Something like:
confuse.Template({
'urls' confuse.Dict(default=REQUIRED) : {
'first': confuse.String(),
'second': confuse.String(),
}
}),
sampsyo commented
Aha, you do not want to wrap the entire thing in confuse.Template
. Just use the dictionary directly, like this:
>>> data = {'other_key': 'something'}
>>> config = confuse.RootView([confuse.ConfigSource.of(data)])
>>> config.get(confuse.Template({'key': confuse.String()})) # this is what you were doing
{'other_key': 'something'}
>>> config.get({'key': confuse.String()}) # this is what you should do
Traceback (most recent call last):
[...]
confuse.exceptions.NotFoundError: key not found
Also, that default=REQUIRED
is not necessary (things are required by default).
dsalaza4 commented
Thank you!