知识卡片
None区别未传与假值
可选布尔查询参数需要区分“没有传”与“传了 false”。书中先判断 cancelled is not None,再按 true 或 false 分别筛选已取消或未取消订单;若只写 if cancelled,false 会被误当成未传,过滤意图就丢失。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
原书出处
参考来源
- 位置:《Microservice APIs》第 6 章《Building REST APIs with Python》(源文件:_epub-src/OEBPS/Text/06.htm)
- 结论依据:原文要求先用 None 判断参数是否设置,示例代码随后在 `cancelled` 为真与假时走不同过滤分支。
- 原始内容:Since the query parameters are optional, we’ll first check whether they’ve been set. We can do that by checking whether their values are something other than None . ... if cancelled is not None: ③ if cancelled: query_set = [ order for order in query_set if order['status'] == 'cancelled' ] else: query_set = [ order for order in query_set if order['status'] != 'cancelled' ]