FastAPI密码验证错误未正确显示
我正在用Fast API进行一个简单的身份验证操作。当用户登录时,如果密码长度少于6个字符,我想返回一个错误信息,我是这样做的。
class AuthSchema(BaseModel):
email: str
password: constr(min_length=6)
@validator("password")
def validate_password(cls, value):
if len(value) < 6:
raise HTTPException(status_code=400, detail="Password must be at least 6 characters long")
return value
@router.post("/login", response_model=CustomResponse)
async def login_user(user: AuthSchema, db: Session = Depends(db.get_session)):
try:
if not UserServices().verify_user_password(db, user.email, user.password):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid credentials"
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e)
)
token = token_services.create_access_token({
"id": user.id,
"role": user.role
})
return CustomResponse(
message="User logged in successfully",
data={
"token": token
},
status=200
)
代码是这样的,但是它返回的错误信息如下
{
"detail": [
{
"type": "string_too_short",
"loc": [
"body",
"password"
],
"msg": "String should have at least 6 characters",
"input": "123",
"ctx": {
"min_length": 6
},
"url": "https://errors.pydantic.dev/2.6/v/string_too_short"
}
]
}
这是什么原因呢?或者有没有其他方法可以返回这个错误?谢谢大家的回答。
pydantic==2.6.3
fastapi==0.110.0
1 个回答
0
在你的 AuthSchema 模型中,有一个叫做 constr(min_length=6)
的限制。这意味着密码的最小长度必须是6个字符。当 FastAPI 把 HTTP 请求的内容转换成模型时,它会等待来自 Pydantic 的 ValueError
异常。一旦收到这个异常,FastAPI 就会把它转化为一个 HTTPException
,这就意味着它会发送一个状态码为 422 的响应,而根本不会执行你的代码。如果你想使用自己的错误处理方式,只需要像下面这样去掉 constr
的限制:
class AuthSchema(BaseModel):
email: str
password: str
然后在 UserService
的方法中检查密码的长度。