Skip to content

Commit 806cfa3

Browse files
committed
fix(main.py): Custom JSON Schema for PydanticObjectId
Attempt to fix pydantic serialization errors Signed-off-by: Denys Fedoryshchenko <denys.f@collabora.com>
1 parent a68ee8a commit 806cfa3

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

api/main.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import re
1313
import asyncio
1414
import traceback
15-
from typing import List, Union, Optional
15+
from typing import List, Union, Optional, Any
1616
from datetime import datetime
1717
from contextlib import asynccontextmanager
1818
from fastapi import (
@@ -82,8 +82,22 @@ async def lifespan(app: FastAPI): # pylint: disable=redefined-outer-name
8282
auth = Authentication(token_url="user/login")
8383
pubsub = None # pylint: disable=invalid-name
8484

85+
86+
class CustomObjectId(PydanticObjectId):
87+
@classmethod
88+
def __get_pydantic_json_schema__(cls, core_schema: Any, handler: GetCoreSchemaHandler) -> dict[str, Any]:
89+
json_schema = handler(core_schema)
90+
# Indicate that this field should be treated like a string
91+
# with a pattern matching a 24-character hex string
92+
json_schema.update({
93+
"type": "string",
94+
"pattern": "^[0-9a-fA-F]{24}$"
95+
})
96+
return json_schema
97+
98+
8599
auth_backend = auth.get_user_authentication_backend()
86-
fastapi_users_instance = FastAPIUsers[User, PydanticObjectId](
100+
fastapi_users_instance = FastAPIUsers[User, CustomObjectId](
87101
get_user_manager,
88102
[auth_backend],
89103
)

0 commit comments

Comments
 (0)