【发布时间】: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,“性别”:“男性”} 这现在有效,但一切都是强制性的。以下是我的问题:
- 如果性别是可选的怎么办?还是我想添加一个新的数据点进行测试,而不破坏所有现有的应用程序调用 API?
- 如果某些内容是可选的,我该如何处理 DB 插入?我需要创建所有可能组合的变体吗?或者我可以插入空值,所以我只有一个插入语句吗?
【问题讨论】: