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
Yes. The
args
attribute of a Flask/WerkzeugRequest
object is anImmutableMultiDict
, which is a subclass ofMultiDict
. TheMultiDict.get()
method accepts atype
argument which does exactly what you want:Here's the relevant section of the docs: