request.args.get 的 type 参数有点误导,因为它不是用于指定值的类型,而是用于指定 可调用:
-
type – 用于在 MultiDict 中转换值的可调用对象。如果此可调用对象引发 ValueError,则返回默认值。
它接受一个可调用对象(例如一个函数),将该可调用对象应用于查询参数值,然后返回结果。所以代码
request.args.get("fullInfo", default=False, type=bool)
调用bool(value),其中value 是查询参数值。但在 Flask 中,查询参数值始终存储为字符串。不幸的是,在非空字符串上调用 bool() 将始终是 True:
In [10]: bool('true')
Out[10]: True
In [11]: bool('false')
Out[11]: True
In [12]: bool('any non-empty will be true')
Out[12]: True
In [13]: bool('')
Out[13]: False
除了bool,您可以传递一个函数来显式检查字符串是否等于文字字符串true(或您的API规则认为是真实的任何值):
full_info = request.args.get('fullInfo', default=False, type=lambda v: v.lower() == 'true')
return jsonify({'full_info': full_info})
$ curl -XGET http://localhost:5000/test?fullInfo=false
{"full_info":false}
$ curl -XGET http://localhost:5000/test?fullInfo=adasdasd
{"full_info":false}
$ curl -XGET http://localhost:5000/test?fullInfo=11431423
{"full_info":false}
$ curl -XGET http://localhost:5000/test?fullInfo=
{"full_info":false}
$ curl -XGET http://localhost:5000/test?fullInfo=true
{"full_info":true}
$ curl -XGET http://localhost:5000/test?fullInfo=TRUE
{"full_info":true}
$ curl -XGET http://localhost:5000/test
{"full_info":false}