FastApi-使用嵌套模型给出JSON序列化错误

发布于 2025-01-25 17:40:06 字数 2046 浏览 2 评论 0原文

我正在尝试在帖子通话中使用嵌套模型。目标是使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一紙繁鸢 2025-02-01 17:40:06

我解决了。问题在于文件create_user.py

我使用vars()将我的用户变成dict的用户对象(与JSON不一样的东西) )但是,我需要使用FastAPI Framework提供的适当的JSON编码器。

旧代码:

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}")

新代码:

def create_new_keycloak_user(user: User):
    admin = keycloak_service.connect_to_keycloak_as_admin()
    try:
        body = jsonable_encoder(user)
        admin.create_user(body)
    except Exception as err:
        raise HTTPException(status_code=400, detail=f"User creation failed: {err}")

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:

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}")

NEW CODE:

def create_new_keycloak_user(user: User):
    admin = keycloak_service.connect_to_keycloak_as_admin()
    try:
        body = jsonable_encoder(user)
        admin.create_user(body)
    except Exception as err:
        raise HTTPException(status_code=400, detail=f"User creation failed: {err}")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文