[英]Dependency injection data model in FastAPI
I'm very new to FastAPI.我对 FastAPI 很陌生。 I have a request which looks something like this:
我有一个看起来像这样的请求:
@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),
):
Now, the EducationCreation
data model has a field called customer_id
.现在,
EducationCreation
数据 model 有一个名为customer_id
的字段。 I want to check if the customer_id
exists in the database.我想检查数据库中是否存在
customer_id
。 Now, I know that I can manually do that within the function itself and it is not recommended to do database related validation in Schema
.现在,我知道我可以在 function 本身内手动执行此操作,不建议在
Schema
中进行与数据库相关的验证。 Is there any way to check if the customer_id
exists in the database using dependencies
?有没有办法使用
dependencies
项检查数据库中是否存在customer_id
? Is there something like this:有没有这样的东西:
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),
):
You could do that by declaring the parameter in the dependency function, as described in the documentation .您可以通过在依赖项 function 中声明参数来做到这一点,如文档中所述。 If the
customer_id
exists in the database, then return the data to the route.如果数据库中存在
customer_id
,则将数据返回给路由。 If not, you could then raise an HTTPException
, or handle it as desired.如果没有,您可以引发
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),
):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.