bauerji / flask-pydantic

flask extension for integration with the awesome pydantic package
MIT License
352 stars 56 forks source link

TypeError: Object of type ValueError is not JSON serializable #84

Open kakakikikeke-fork opened 8 months ago

kakakikikeke-fork commented 8 months ago

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

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'
TypeError: Object of type ValueError is not JSON serializable
{
  "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.

yctomwang commented 7 months ago

@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

sonarcloud[bot] commented 7 months ago

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

yctomwang commented 7 months ago

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!

kakakikikeke-fork commented 7 months ago

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.

yctomwang commented 7 months ago

@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.