Untitled
unknown
plain_text
2 years ago
1.1 kB
10
Indexable
import json from typing import Optional, List from datetime import date from fastapi.encoders import jsonable_encoder from pydantic import ValidationError from pydantic.types import NonNegativeInt from sqlmodel import SQLModel class DraftTest(SQLModel): name: Optional[str] age: Optional[str] dob: Optional[str] errors: Optional[List] = [] class ProperTest(SQLModel): name: str = "test" age: NonNegativeInt dob: date obj = {'name': 'Magda', 'age': '-31', 'dob': 'zsdzds1991-06-26'} x = DraftTest(**obj) try: y = ProperTest(**obj) except ValidationError as e: for error in e.errors(): x.errors.append({"loc": error["loc"][0], "msg": error["msg"]}) json_compatible_x = jsonable_encoder(x) json_x = json.dumps(json_compatible_x, indent=4) print(json_x) # OUTPUTS: # { # "name": "Magda", # "age": "-31", # "dob": "zsdzds1991-06-26", # "errors": [ # { # "loc": "age", # "msg": "ensure this value is greater than or equal to 0" # }, # { # "loc": "dob", # "msg": "invalid date format" # } # ] # }
Editor is loading...