[英]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:以下是我的问题:
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.