Closed nor3th closed 2 years ago
this is wrong. json
shoud be A JSON serializable Python object.
response = requests.post(url="localhost:5000/path/", json=mymodel.json())
i think.
response = requests.post(url="localhost:5000/path/", json=mymodel.dict())
resp = requests.post("http://localhost:5000/", data=mymodel.json(), headers={
"content-type": "application/json"
})
Hey @mkdir700
I agree that the approach with
response = requests.post(url="localhost:5000/path/", json=mymodel.json())
is wrong. My point is though that ideally flask-opencti3
would handle a type mismatch better, than throwing an unhandled exception where it is not very obvious for the developer to see what the issue is.
One alternative would be to either check the value type before using the value like here https://github.com/luolingchun/flask-openapi3/blob/master/flask_openapi3/do_wrapper.py#L73-L87 So a solution could be to do (here https://github.com/luolingchun/flask-openapi3/blob/master/flask_openapi3/do_wrapper.py#L92-L96):
value = request.get_json(silent=True, force=True) or {}
if body.__custom_root_type__:
# https://pydantic-docs.helpmanual.io/usage/models/#custom-root-types
body_ = body(__root__=value)
else:
body_ = body(**value)
or to set value to
value = request.get_json(silent=True, force=True) or {}
if not isinstance(value, dict):
raise ValidationError(f"Unable to process content {value} of type {type(value)}!")
if body.__custom_root_type__:
# https://pydantic-docs.helpmanual.io/usage/models/#custom-root-types
body_ = body(__root__=value)
else:
body_ = body(**value)
Regards
To improve the robustness, I will fix it.
Support for converting str
to dict
, which will raise 422
exceptions if the conversion is wrong.
release v2.0.0rc2
First off thank you very much for your great library. Exactly what I was looking for!!!
Environment:
Using for example this model
and the flask server is looking for the model as body
, but the user sends the model json formated (thus as
str
instead of adict
)The wrapper throws an exception, since a
str
can't be mapped to the MyModel like adict
An alternative would be to either do attempt a
json.loads()
before doing abody(**value)
or to return 422?