【问题标题】:422 Unprocessable Entity in FastAPI when returning response返回响应时,FastAPI 中的 422 无法处理实体
【发布时间】:2022-10-07 17:00:05
【问题描述】:

我正在使用 FastAPI 进行机器学习推理和返回响应。有两个任务由task_id 控制。对于task_id=0,solvent 和solute 都需要在使用task_id=1 时返回响应,我只需要solute。但是在为键提供值时,需要在我不需要的task_id=1 中提供solvent 值。如果没有给出我得到的值422 Unprocessable Entity。如果在使用task_id=1 时未提供溶剂值,他们是否有办法做到这一点,这样它就不会抛出错误?

@app.get(\'/predict\')
async def predict(task_id:int, background_tasks: BackgroundTasks,solute,solvent):
    global task_id_global
    task_id_global = task_id
    if task_id == 0:
        background_tasks.add_task(predictions,solute,solvent)
        return {\'success\'}
    elif task_id == 1:
        # solvent = None
        background_tasks.add_task(predictions_two,solute)
        return {\'success\'}
    else:
        return \"Give proper task_id\"

    标签: python fastapi


    【解决方案1】:

    将您的参数声明为Optional。例如:

    from typing import Optional
    ...
    async def predict(solvent: Optional[str] = None):
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多