【问题标题】:Dependency injection data model in FastAPIFastAPI 中的依赖注入数据模型
【发布时间】:2022-08-12 12:52:46
【问题描述】:

我对 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 中进行与数据库相关的验证。有没有办法使用dependencies检查数据库中是否存在customer id?有没有这样的东西:

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),
):
  • 是的,你可以做到。您将需要能够访问 check_customer_exists 函数中的客户字段并引发 HTTPException 或返回 EducationCreation 类型的数据
  • 如何访问check_customer_exists中的customer id?如果 check_customer_exists 有任何参数,它会引发 422 并表示缺少该值。 @isabi
  • Chris\'s 的回复速度比我快,并提供了正确的答案

标签: python flask fastapi pydantic


【解决方案1】:

您可以通过在依赖函数中声明参数来做到这一点,如documentation 中所述。如果数据库中存在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),
):

【讨论】:

  • 我之前确实接受过。可能由于网络问题,没有发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2018-01-16
  • 1970-01-01
  • 2021-04-17
  • 2016-02-11
  • 1970-01-01
相关资源
最近更新 更多