From 69ca40b777fb1bd047264143d114a651173e4ffc Mon Sep 17 00:00:00 2001 From: Denys Fedoryshchenko Date: Thu, 12 Dec 2024 23:46:17 +0200 Subject: [PATCH] fix(main.py): Custom JSON Schema for PydanticObjectId Attempt to fix pydantic serialization errors Signed-off-by: Denys Fedoryshchenko --- api/main.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/api/main.py b/api/main.py index a664dedb..ba9127f6 100644 --- a/api/main.py +++ b/api/main.py @@ -82,8 +82,22 @@ async def lifespan(app: FastAPI): # pylint: disable=redefined-outer-name auth = Authentication(token_url="user/login") pubsub = None # pylint: disable=invalid-name + +class CustomObjectId(PydanticObjectId): + @classmethod + def __get_pydantic_json_schema__(cls, core_schema: Any, handler: GetCoreSchemaHandler) -> dict[str, Any]: + json_schema = handler(core_schema) + # Indicate that this field should be treated like a string + # with a pattern matching a 24-character hex string + json_schema.update({ + "type": "string", + "pattern": "^[0-9a-fA-F]{24}$" + }) + return json_schema + + auth_backend = auth.get_user_authentication_backend() -fastapi_users_instance = FastAPIUsers[User, PydanticObjectId]( +fastapi_users_instance = FastAPIUsers[User, CustomObjectId]( get_user_manager, [auth_backend], )