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规则,可以被视为真值的任何值):
def is_it_true(value):
return value.lower() == 'true'
@app.route("/test")
def test():
full_info = request.args.get('fullInfo', default=False, type=is_it_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}