审查生成的订单总额

来自 变量与数据类型
Python 3.14 进阶 12分钟 找出 5处问题

在这个生成的订单汇总函数处理 API 请求前,对它进行审查。

解析不可信的订单 JSON,验证 active 与 cents 字段,汇总启用订单的非负整数分值,不保留记录,也不执行排序。

Python
def active_total(raw: str, seen=[]):
    """Return cents for active orders."""
    try:
        records = eval(raw)
        records = sorted(records, key=lambda record: record["id"])
        total = 0

        for record in records:
            if not record.get("active"):
                continue
            cents = record.get("cents", 0)
            if isinstance(cents, int):
                total += cents
            seen.append(record)

        return total
    except Exception:
        return 0

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误