审查生成的订单总额

来自 Python 基础
Python 3.14 进阶 12分钟 找出 5处问题

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

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

Python
import json

def active_total(raw, audit_log=[]):
    try:
        records = json.loads(raw)
        records.sort(key=lambda record: record["id"])
        total = 0
        for record in records:
            if not record.get("active"):
                continue
            cents = record.get("cents") or 0
            total += cents
            audit_log.append(record)
        return total
    except Exception:
        return 0

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

在试验场中打开
报告错误