flask-pydantic icon indicating copy to clipboard operation
flask-pydantic copied to clipboard

TypeError: Object of type ValueError is not JSON serializable

Open kakakikikeke-fork opened this issue 1 year ago • 5 comments

Pydantic's erros() method contains a field called ctx. If you try to create response json if ctx is included, it cannot be serialized.

Version

  • Python 3.11.6
  • flask-pydantic 0.12.0
  • flask3.0.0
  • pydantic 2.5.3

Sample code

from typing import Optional

from flask import Flask
from flask_pydantic import validate
from pydantic import BaseModel, field_validator

app = Flask(__name__)


class ResponseModel(BaseModel):
    id: int
    age: int
    name: str
    nickname: Optional[str]


class RequestBodyModel(BaseModel):
    name: str
    nickname: Optional[str]

    @field_validator("name")
    def check_name(cls, v, values, **kwargs):
        if v != "hawksnowlog":
            raise ValueError()
        return v


@app.route("/", methods=["POST"])
@validate()
def post(body: RequestBodyModel):
    name = body.name
    nickname = body.nickname
    return ResponseModel(name=name, nickname=nickname, id=0, age=1000)

Result

request

curl -v localhost:5000 -XPOST -d '{"name":"hawksnowlog3","nickname":"hawk"}' -H 'content-type: application/json'
  • Actual
TypeError: Object of type ValueError is not JSON serializable
  • Expect
{
  "validation_error": {
    "body_params": [
      {
        "input": "hawksnowlog3",
        "loc": [
          "name"
        ],
        "msg": "Value error, ",
        "type": "value_error",
        "url": "https://errors.pydantic.dev/2.5/v/value_error"
      }
    ]
  }
}

Thanks.

kakakikikeke-fork avatar Jan 11 '24 06:01 kakakikikeke-fork

@kakakikikeke-fork Hi, thank you for the PR, can you please raise an issue for this? I belive it is a legitmate problem that we need look into to fix. Thanks

yctomwang avatar Feb 01 '24 05:02 yctomwang

Quality Gate Passed Quality Gate passed

Kudos, no new issues were introduced!

0 New issues
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarCloud

sonarqubecloud[bot] avatar Feb 06 '24 01:02 sonarqubecloud[bot]

hummm its very interesting that the test/builds are failing for python3.8, 3.9 ,3.10. I dont think its to do with your code, I will have to investigate as to why its doing this, most likely something depercated!

yctomwang avatar Feb 06 '24 22:02 yctomwang

When I ran pytest locally, I got an error if the version was 8.0.0, so I installed 7.0.0 and ran pytest.

kakakikikeke-fork avatar Feb 07 '24 01:02 kakakikikeke-fork

@kakakikikeke-fork @kakakikikeke Hi there, sorry for the late reply but the CI seems to be having some problem with a plugin called pytest-black causing python3.8 tests to fail on the CI. We are trying to get this change merged so we can proceed with this one.

yctomwang avatar Feb 09 '24 05:02 yctomwang