我对 FastAPI 很陌生。我有一个请求,看起来像这样:
@router.post("/", response_model=EducationInResp)
async def create_Education_account(
education_in: EducationCreation,
current_user=Depends(get_current_user),
has_perm=Depends(user_has_create_perms),
):
现在EducationCreation
数据模型有一个名为customer_id
。我想检查一下是否customer_id
存在于数据库中。现在,我知道我可以在函数本身内手动执行此操作,并且不建议在中进行与数据库相关的验证Schema
。有什么方法可以检查是否customer_id
存在于数据库中使用dependencies
?有没有这样的事情:
async def check_customer_exist(some_val):
# some operation here to check and raise exception
@router.post("/", response_model=EducationInResp)
async def create_Education_account(
education_in: EducationCreation = Depends(check_customer_exist),
current_user=Depends(get_current_user),
has_perm=Depends(user_has_create_perms),
):
您可以通过在依赖函数中声明参数来做到这一点,如文档。如果customer_id
存在于数据库中,则将数据返回给路由。如果没有,您可以提出HTTPException,或根据需要进行处理。
from fastapi.exceptions import HTTPException
customer_ids = [1, 2, 3]
async def check_customer_exist(education_in: EducationCreation):
if education_in.customer_id not in customer_ids: # here, check if the customer id exists in the database.
raise HTTPException(status_code=404, detail="Customer ID not found")
else:
return education_in
@router.post("/", response_model=EducationInResp)
async def create_Education_account(
education_in: EducationCreation = Depends(check_customer_exist),
current_user=Depends(get_current_user),
has_perm=Depends(user_has_create_perms),
):
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)