python - Is there a shorter/better way to validate request params? -
i keep repeating blocks validate request params. there shorter/better way implement this?
count = request.args.get('count', default_count) if count: try: count = int(count) except valueerror: count = default_count
yes. args
attribute of flask/werkzeug request
object immutablemultidict
, subclass of multidict
. multidict.get()
method accepts type
argument want:
count = request.args.get('count', default_count, type=int)
here's relevant section of docs:
get(key, default=none, type=none)
return default value if requested data doesn’t exist. if
type
provided , callable should convert value, return or raisevalueerror
if not possible. in case function return default if value not found:>>> d = typeconversiondict(foo='42', bar='blub') >>> d.get('foo', type=int) 42 >>> d.get('bar', -1, type=int) -1
Comments
Post a Comment