FastApi-使用嵌套模型给出JSON序列化错误
我正在尝试在帖子通话中使用嵌套模型。目标是使用API在我的KeyCloak实例中创建用户,因此我按照我需要的模型创建了文档。
当我尝试使用我的API使用Postman创建用户时,FastAPI给我以下错误:
类型属性的对象不是JSON序列化
代码如下:
user.py
from pydantic import BaseModel
# TODO Error: Object of type Attributes is not JSON serializable.
class Attributes(BaseModel):
locale: str
phoneNumber: str
class Config:
orm_mode = True
class Credentials(BaseModel):
value: str
type: str
class Config:
orm_mode = True
class User(BaseModel):
email: str
username: str
enabled: bool
firstName: str
lastName: str
attributes: Attributes
credentials: list[Credentials]
class Config:
orm_mode = True
create_user.py
def create_new_keycloak_user(user: User):
admin = keycloak_service.connect_to_keycloak_as_admin()
try:
body = vars(user)
print(body)
new_user = admin.create_user(body)
return new_user
except Exception as err:
raise HTTPException(status_code=400, detail=f"User creation failed: {err}")
routing.py
# I also have tried without response_model=User
@router.post("/create-user", response_model=User)
async def create_new_user(user: User):
create_user.create_new_keycloak_user(user)
return user
当我尝试创建用户时,我在后端收到的正文:
{'email': '[email protected]', 'username': 'mverdi', 'enabled': True, 'firstName': 'Jhon', 'lastName': 'Doe', 'attributes': Attributes(locale='ITA', phoneNumber='+391234567891'), 'credentials': [Credentials(value='superpassword01', type='password')]}
我认为它与此相关“畸形” JSON,如果您在上一个JSON中注意到
'attributes': Attributes(locale='ITA', phoneNumber='+391234567891'),
,显然不允许以适当的JSON格式这样的事情。但是,为什么我会收到这样的事情呢?
将FastApi与Python3.10和Pydantic一起使用
I'm trying to use nested models in a POST call. The goal is to create a user in my Keycloak instance with an API, so I have created following the documentation the model that I need.
When I try to create the user with Postman using my API, fastAPI gives me the following error:
Object of type Attributes is not JSON serializable
The code is the following:
user.py
from pydantic import BaseModel
# TODO Error: Object of type Attributes is not JSON serializable.
class Attributes(BaseModel):
locale: str
phoneNumber: str
class Config:
orm_mode = True
class Credentials(BaseModel):
value: str
type: str
class Config:
orm_mode = True
class User(BaseModel):
email: str
username: str
enabled: bool
firstName: str
lastName: str
attributes: Attributes
credentials: list[Credentials]
class Config:
orm_mode = True
create_user.py
def create_new_keycloak_user(user: User):
admin = keycloak_service.connect_to_keycloak_as_admin()
try:
body = vars(user)
print(body)
new_user = admin.create_user(body)
return new_user
except Exception as err:
raise HTTPException(status_code=400, detail=f"User creation failed: {err}")
routing.py
# I also have tried without response_model=User
@router.post("/create-user", response_model=User)
async def create_new_user(user: User):
create_user.create_new_keycloak_user(user)
return user
The body I receive in the backend when I try to create user:
{'email': '[email protected]', 'username': 'mverdi', 'enabled': True, 'firstName': 'Jhon', 'lastName': 'Doe', 'attributes': Attributes(locale='ITA', phoneNumber='+391234567891'), 'credentials': [Credentials(value='superpassword01', type='password')]}
I think it's related to this "malformed" JSON, if you notice in the previous JSON I have
'attributes': Attributes(locale='ITA', phoneNumber='+391234567891'),
which is clearly not allowed a thing like this in a properly JSON format. But why I receive as result a thing like that?
Using FastAPI with Python3.10 and Pydantic
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我解决了。问题在于文件
create_user.py
我使用
vars()
将我的用户变成dict的用户对象(与JSON不一样的东西) )但是,我需要使用FastAPI Framework提供的适当的JSON编码器。旧代码:
新代码:
I solved it. The problem was in the file
create_user.py
I was converting my user object with
vars()
who turns my user into a dict (which is not the same thing as a JSON) but instead I needed to use a proper json encoder provided by FastAPI framework.OLD CODE:
NEW CODE: