You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI异步函数process_invoice_items为何返回None?

问题分析与解决方案

核心问题排查

  • 缺失itemgetter导入引发未捕获异常
    helpers.py的calculate_invoicing函数中使用了itemgetter,但未导入from operator import itemgetter,会触发NameError。而process_invoice_items仅捕获TypeError,该异常无法被处理,导致函数提前终止,无返回值,最终返回None。

  • 异常捕获范围过窄且无兜底返回
    process_invoice_items的try块仅处理TypeError,其他类型异常(如上述NameError)会直接导致函数无返回值;即使捕获到TypeError,函数仅打印日志,未返回任何内容,同样会返回None。

  • 输入参数类型不匹配(潜在风险)
    若invoice.items并非预期的列表类型(如None或非可迭代对象),会触发TypeError,此时函数捕获异常后无返回值,返回None。需确认CreateInvoiceRequest中items字段的定义是否正确。

修复步骤

  1. 补充必要导入
    在helpers.py顶部添加:

    from operator import itemgetter
    
  2. 优化异常处理逻辑
    修改process_invoice_items函数,扩大异常捕获范围,并添加兜底返回值:

    async def process_invoice_items(invoice_items: list):
        """
        Generate data about invoice.items properly grouped.
        :param invoice_items: list containing data about items in the request
        :return: list contained all items grouped by amount and description
        """
        try:
            invoice_data: dict = await calculate_invoicing(invoice_items)
            invoice_report: list = await generate_report(invoice_data)
            return invoice_report
        except Exception as e:
            error(f"Something wrong happening while grouping invoice.items: {str(e)}")
            return []  # 返回空列表避免返回None
    
  3. 验证输入参数定义
    确认CreateInvoiceRequest中items字段类型正确,示例:

    from pydantic import BaseModel
    from typing import List, Dict
    
    class CreateInvoiceRequest(BaseModel):
        items: List[Dict[str, any]]
        # 其他字段...
    

内容的提问来源于stack exchange,提问作者Guilherme Massoqueto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:51:13