Is there a shorter/better way to validate request params?

3.2k views Asked by At

I keep repeating blocks like this to validate request params. Is there a shorter/better way to implement this?

count = request.args.get('count', DEFAULT_COUNT)
if count:
    try:
        count = int(count)
    except ValueError:
        count = DEFAULT_COUNT
1

There are 1 answers

0
Zero Piraeus On BEST ANSWER

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 a ValueError 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