1

I'm implementing some REST API with flask. In one of the APIs, I need to submit a location defined by longitude and latitude. So naturally I'm doing this with httpie:

http POST :5000/api/v1.0/foo lng=12.34 lat=56.78

At the flask end, I'm using voluptuous to validate the JSON data. However, all the data that's received at the back end is of unicode type. I have to do something like this:

try:
  lng = atof(data['lng'])
  schema(data)
except KeyError:
  raise SomeError
except MultipleInvalid:
  raise SomeError

This feels clunky and kind of beat the purpose of voluptuous. Am I doing in a wrong way or, is there a better way?

lang2
  • 11,433
  • 18
  • 83
  • 133

1 Answers1

2

Yes, this library has the ability to coerce values to floats or integers (using Coerce). For example:

>>> from voluptuous import *
>>> schema = Schema(Coerce(float))
>>> schema('1.10')
1.1
>>> schema(2.2)
2.2

This means it'll accept plain floats but also (Unicode) strings that can be converted to a float. The resulting value is a float.

You can also combine several validators and the float value will be passed onto the next validator:

schema = Schema(All(Coerce(float), Range(min=200)))

This schema will validate that the input value can be coerced to a float and that the float value is at least 200.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180