从请求中获取布尔值

Fetching boolean value from request

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

示例 url:

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 方法来做到这一点?

为什么不简单:

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

True != False  # >>> True
False != False  # >>> False
None != False  # >>> True
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