Is there a shorter/better way to validate request params?
Yes. The args
attribute of a Flask/Werkzeug Request
object is an ImmutableMultiDict
, which is a subclass of MultiDict
. The MultiDict.get()
method accepts a type
argument which does exactly what you want:
count = request.args.get('count', DEFAULT_COUNT, type=int)
Here's the relevant section of the docs:
get(key, default=None, type=None)
Return the default value if the requested data doesn’t exist. If
type
is provided and is a callable it should convert the value, return it or raise aValueError
if that is not possible. In this case the function will return the default as if the value was not found:
>>> d = TypeConversionDict(foo='42', bar='blub')>>> d.get('foo', type=int)42>>> d.get('bar', -1, type=int)-1