是否有 shorter/better 方法来验证请求参数?
Is there a shorter/better way to validate request params?
我一直重复这样的块来验证请求参数。有没有 shorter/better 方法来实现这个?
count = request.args.get('count', DEFAULT_COUNT)
if count:
try:
count = int(count)
except ValueError:
count = DEFAULT_COUNT
是的。 args
attribute of a Flask/Werkzeug Request
object is an ImmutableMultiDict
, which is a subclass of MultiDict
. The MultiDict.get()
方法接受一个 type
参数,它完全符合您的要求:
count = request.args.get('count', DEFAULT_COUNT, type=int)
这是文档的相关部分:
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
我一直重复这样的块来验证请求参数。有没有 shorter/better 方法来实现这个?
count = request.args.get('count', DEFAULT_COUNT)
if count:
try:
count = int(count)
except ValueError:
count = DEFAULT_COUNT
是的。 args
attribute of a Flask/Werkzeug Request
object is an ImmutableMultiDict
, which is a subclass of MultiDict
. The MultiDict.get()
方法接受一个 type
参数,它完全符合您的要求:
count = request.args.get('count', DEFAULT_COUNT, type=int)
这是文档的相关部分:
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 aValueError
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