Skip to content

Commit b74e469

Browse files
committed
Add warp function for pydantic model json dump
Signed-off-by: Wei-Chun, Chang <[email protected]>
1 parent 5a2d649 commit b74e469

File tree

4 files changed

+22
-3
lines changed

4 files changed

+22
-3
lines changed

recce/apis/check_api.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from recce.apis.run_func import submit_run
1111
from recce.exceptions import RecceException
1212
from recce.models import RunType, RunDAO, Check, CheckDAO, Run
13+
from recce.models.util import pydantic_model_json_dump
1314

1415
check_router = APIRouter(tags=['check'])
1516

@@ -240,7 +241,7 @@ async def export_handler():
240241
from ..models.state import recce_state
241242

242243
try:
243-
return recce_state.model_dump_json()
244+
return pydantic_model_json_dump(recce_state)
244245
except RecceException as e:
245246
raise HTTPException(status_code=400, detail=e.message)
246247

recce/models/state.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from pydantic import BaseModel, Field
99

1010
from .types import Run, Check
11+
from .util import pydantic_model_json_dump
1112
from .. import get_version
1213

1314
logger = logging.getLogger('uvicorn')
@@ -28,7 +29,7 @@ def store(self, file_path):
2829
self.metadata = RecceStateMetadata()
2930
start_time = time.time()
3031
logger.info(f"Store recce state to '{file_path}'")
31-
json_data = self.model_dump_json()
32+
json_data = pydantic_model_json_dump(self)
3233
with open(file_path, 'w') as f:
3334
f.write(json_data)
3435
end_time = time.time()

recce/models/util.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pydantic.version
2+
from pydantic import BaseModel
3+
4+
from recce.exceptions import RecceException
5+
6+
7+
def pydantic_model_json_dump(model: BaseModel):
8+
pydantic_version = pydantic.version.VERSION
9+
pydantic_major = pydantic_version.split(".")[0]
10+
11+
if pydantic_major == "1":
12+
return model.json()
13+
elif pydantic_major == "2":
14+
return model.model_dump_json()
15+
else:
16+
raise RecceException("Currently only support pydantic version 1 and 2.")

tests/models/test_state.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from recce.models import RunType, Run, RunDAO, CheckDAO, Check
44
from recce.models.state import RecceState
5+
from recce.models.util import pydantic_model_json_dump
56

67

78
def test_load():
@@ -13,7 +14,7 @@ def test_load():
1314
RunDAO(state).create(run)
1415
CheckDAO(state).create(check)
1516

16-
json_data = state.json()
17+
json_data = pydantic_model_json_dump(state)
1718
new_state = RecceState(**json.loads(json_data))
1819

1920
run_loaded = new_state.runs[0]

0 commit comments

Comments
 (0)