返回响应模型作为JSON响应中的值



我想让我的查询返回如下内容:

{"message": "OK",
"data": {
"username": "string",
"pseudo": "string",
"email": "string"}
}

但是我不能让我的模型返回JSON内,我只能返回模型,所以它给出了:

{
"username": "string",
"pseudo": "string",
"email": "string"
}

这是我试图运行以获得第一个代码片段

的代码
@app.post("/", response_model=_models.UserOut, status_code=status.HTTP_201_CREATED)
def postUser(userPost: _models.UserIn):
if not userPost.regex_check_email(userPost.email):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Email: {userPost.email} not valid format")
if not userPost.regex_check_username(userPost.username):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Username: {userPost.username} not valid format")
else:
db_user.append(userPost)
return {"message": "OK",
"data": userPost}

,我的模型:

class UserOut(BaseModel):
username: str
pseudo: Optional[str] = None
email: str

class UserIn(UserOut):
username: str
pseudo: Optional[str] = None
email: str
password: str
def regex_check_email(self, email):
match = re.match(email_regex, email)
is_match_email = bool(match)
return is_match_email
def regex_check_username(self, username):
match = re.match(username_regex, username)
is_match_username = bool(match)
return is_match_username

这只返回me

pydantic.error_wrappers。ValidationError: 2个验证错误UserOut响应->必需的用户名字段(type=value_error.missing) response ->电子邮件字段必需(type = value_error.missing)

如果你能帮助我,告诉我为什么我失败了,那就太好了,我想我没有理解关于反应模型的一切。谢谢。

在POST处理程序的头中使用

@app.post("/", response_model=_models.UserOut ...)
...

所以当你尝试返回不匹配UserOut模型的东西时,它会返回一个错误。创建一个模型,它定义了你的信息和数据结构根据需要和使用,随着response_model

快乐编码

编辑:你试过使用这样的东西吗:(python 3.10+)

class UserData(BaseModel):
username: str
pseudo: Optional[str] = None
email: str
class UserOut(BaseModel):
message: str
data: UserData | None = None

当有疑问时,官方文档通常有示例。