从请求中获取布尔值

时间:2019-06-25 08:45:13

标签: python falconframework

我正在从猎鹰API中的请求中获取一个布尔值。

示例网址:

localhost:8080/api/some-end-point/101?something=true

我想要

----------------------------------
| something     | Something_flag |
----------------------------------
| true          | True           |
----------------------------------
| false         | False          |
----------------------------------
| not provided  | True           |
----------------------------------

代码:

something_flag = req.get_param_as_bool('something') \
        if req.get_param_as_bool('something') else True

是否有任何更好 pythonic方式来做到这一点?

2 个答案:

答案 0 :(得分:1)

something_flag = req.get_param_as_bool('something') \
        if req.get_param('something') is not None else True

或者您可以使用参数default

something_flag = req.get_param_as_bool('something', default=True)

对于1.2版,没有default,您可以使用required

try:
    something_flag = req.get_param_as_bool('something', required=True)
except HTTPBadRequest:
    something_flag = True

答案 1 :(得分:0)

为什么不简单:

something_flag = req.get_param_as_bool('something') != False

True != False  # >>> True
False != False  # >>> False
None != False  # >>> True