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

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -