【问题标题】:In FastAPI can I make a input optional?在 FastAPI 中,我可以将输入设为可选吗?
【发布时间】:2021-11-30 16:20:11
【问题描述】:

为了使我的代码易于管理,我使用类来定义端点的输入。这是一个例子:

class BaseRequest(BaseModel):
    name: str

class details(BaseRequest):
    age: int
    gender: str

@router.put('/people')
async def add_people(body: details):
    try:
        name, age, gender = body.name.upper(), body.age, body.gender

        # insert the person
        res = await main_db_instance.fetch_rows(f"INSERT INTO myDB.people (name, age, gender)"
                                                f" VALUES ('{name}', '{age}', '{gender}')"
                                                f" RETURNING *")
        return JSONResponse(jsonable_encoder(res), status_code=200)

    except Exception as exp:
        logger.exception(f'Exception while inserting the person: {exp}')
        return JSONResponse(status_code=500, content="Error inserting the person")

我会发送这些数据: {“姓名”:“鲍勃”,“年龄”:25,“性别”:“男性”} 这现在有效,但一切都是强制性的。以下是我的问题:

  1. 如果性别是可选的怎么办?还是我想添加一个新的数据点进行测试,而不破坏所有现有的应用程序调用 API?
  2. 如果某些内容是可选的,我该如何处理 DB 插入?我需要创建所有可能组合的变体吗?或者我可以插入空值,所以我只有一个插入语句吗?

【问题讨论】:

    标签: python fastapi


    【解决方案1】:

    为这些字段创建类型 Optional[...] 并为它们提供默认值:

    class BaseRequest(BaseModel):
        name: str
    
    class details(BaseRequest):
        age: int
        gender: Optional[str] = None
    

    如果gender 字段在数据库中可以为空,那么您可以这样做

    res = await main_db_instance.fetch_rows(
        "INSERT INTO myDB.people (name, age, gender) "
        "VALUES (%s, %s, %s) RETURNING *",
        (name, age, gender),
    )
    return JSONResponse(jsonable_encoder(res), status_code=200)
    

    (请参阅使用参数化来避免您的代码目前容易受到的 SQL 注入攻击 - 不确定您的 main_db_instance 是否支持这一点,但确实应该

    【讨论】:

    • 打败我。我认为 = None 不像数据类那样是必需的。
    • 谢谢它的工作(我添加了一条评论它不起作用但这是一个用户错误..显然发送注释掉的 JSON 消息是不可能的)
    • @BradyDean 使用默认值可以完全省略该值。
    猜你喜欢
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    相关资源
    最近更新 更多