Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

voluptuous unable to handle unicode string?

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.

like image 775
lang2 Avatar asked Jul 07 '15 15:07

lang2


1 Answers

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,
})
like image 65
Simeon Visser Avatar answered Oct 12 '22 09:10

Simeon Visser