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 raise valueerror 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

Popular posts from this blog

timeout - Handshake_timeout on RabbitMQ using python and pika from remote vm -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

c# - Search and Add Comment with OpenXML for Word -