简体   繁体   English

在 FastAPI 中,我可以将输入设为可选吗?

[英]In FastAPI can I make a input optional?

To make my code manageable I am using classes to define the inputs into my endpoints.为了使我的代码易于管理,我使用类来定义端点的输入。 Here is an example:这是一个例子:

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")

I would send this data: {"name": "Bob", "age": 25, "gender": "Male" } This works right now but everything is mandatory.我会发送这些数据: {"name": "Bob", "age": 25, "gender": "Male" } 这现在有效,但一切都是强制性的。 Here are my questions:以下是我的问题:

  1. What if gender is optional?如果性别是可选的呢? or do I want to add a new data point to test without breaking all existing apps making API calls?还是我想添加一个新的数据点来测试而不破坏所有现有的应用程序进行 API 调用?
  2. If something is optional, what do I do with the DB inserts?如果某些东西是可选的,我该如何处理 DB 插入? Would I need to create a variation of all possible combinations?我需要创建所有可能组合的变体吗? Or can I insert null values so I just have one insert statement?或者我可以插入 null 值所以我只有一个插入语句吗?

Make the types for those fields Optional[...] and give them default values:将这些字段的类型设为Optional[...]并赋予它们默认值:

class BaseRequest(BaseModel):
    name: str

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

If the gender field is nullable in the database, you can then just do如果数据库中的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)

(see use of parametrization to avoid the SQL injection attacks your code is currently vulnerable to – not sure if your main_db_instance supports that, but it really should ) (请参阅使用参数化来避免您的代码当前容易受到的 SQL 注入攻击 - 不确定您的main_db_instance支持,但确实应该

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM