Skip to main content
 首页 » 编程设计

python之是否有更短/更好的方法来验证请求参数

2025年05月04日34虾米姐

我一直重复这样的 block 来验证请求参数。有没有更短/更好的方法来实现它?

count = request.args.get('count', DEFAULT_COUNT) 
if count: 
    try: 
        count = int(count) 
    except ValueError: 
        count = DEFAULT_COUNT 

请您参考如下方法:

是的。 args Flask/Werkzeug Request 对象的属性是 ImmutableMultiDict,它是 MultiDict 的子类。 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