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

FastAPI中重叠功能的Python端点代码优化建议咨询

FastAPI中重叠功能的Python端点代码优化建议咨询

我现在正在用Python开发FastAPI接口,主要负责处理两种实体对应的请求:

/run/entityA
/run/entityB

这两个接口里,部分参数会根据实体类型不同而变化,但很多参数的处理逻辑是完全重叠的。

当前的实现方式

我现在是分开写两个端点函数:

@router.post("/run/entityA")
def _run_a(args_a):
    # 通用处理逻辑
    # Entity A专属处理逻辑
    # 通用处理逻辑

@router.post("/run/entityB")
def _run_b(args_b):
    # 通用处理逻辑
    # Entity B专属处理逻辑
    # 通用处理逻辑

之前的实现方式

之前我尝试过只用一个端点,把实体相关的参数都设为FastAPI里的Optional类型,然后在函数内部通过if判断来区分处理:

@router.post("/run")
def _run(args):
   # 通用处理逻辑
   if args.entityA_arg:
       # Entity A专属处理逻辑
   if args.entityB_arg:
       # Entity B专属处理逻辑
   # 通用处理逻辑

但我感觉这两种方式都有明显的缺点——分开写会有大量重复的通用代码,合并成一个又会让函数内部逻辑变得混乱,参数校验也不够严谨。想请教大家有没有什么方法能让代码更简洁优雅?

备注:内容来源于stack exchange,提问作者pip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:33:03