Voluptuous, unable to process a Unicode string?

I am trying to use voluptuous to test JSON input from an HTTP request. However, it does not seem to work perfectly with the unicode string.

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 note ufrom the URL, everything works fine. Is this a mistake or am I doing it wrong?

ps. I use python 2.7 if it has anything to do with it.

+4
source share
1 answer

There are two types of strings in Python 2.7: strand unicode. In Python 2.7, a type is strnot a Unicode string, it is a byte string.

, u'http://www.foo.com' str, . str Unicode Python 2.7, :

from voluptuous import Any, Schema, Required

schema = Schema({
    Required('name'): Any(str, unicode),
    Required('www'): Any(str, unicode),
})

, , Unicode, :

schema = Schema({
    Required('name'): unicode,
    Required('www'): unicode,
})
+5

All Articles