I'm trying to use voluptuous to validate JSON input from HTTP request. However, it doesn't seem to handle unicode string to well.
from voluptuous import Schema, Required
from pprint import pprint
schema = Schema({
Required('name'): str,
Required('www'): str,
})
data = {
'name': 'Foo',
'www': u'http://www.foo.com',
}
pprint(data)
schema(data)
The above code generates the following error:
voluptuous.MultipleInvalid: expected str for dictionary value @ data['www']
However, if I remove the u
notation from the URL, everything works fine. Is this a bug or am I doing it wrong?
ps. I'm using python 2.7 if it has anything to do with it.
There are two string types in Python 2.7: str
and unicode
. In Python 2.7 the str
type is not a Unicode string, it is a byte string.
So the value u'http://www.foo.com'
indeed is not an instance of type str
and you're getting that error. If you wish to support both str
and Unicode strings in Python 2.7 you'd need to change your schema to be:
from voluptuous import Any, Schema, Required
schema = Schema({
Required('name'): Any(str, unicode),
Required('www'): Any(str, unicode),
})
Or, for simplicity, if you always receive Unicode strings then you can use:
schema = Schema({
Required('name'): unicode,
Required('www'): unicode,
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With