烧瓶错误处理程序无法正确处理棉花糖ValidationError

时间:2020-10-27 03:20:42

标签: python flask marshmallow flask-restplus

我不知道这是否重要,但实际上我正在使用flask-restplus扩展名。

我所有其他烧瓶错误处理程序均按预期工作,但是由于某种原因,在处理marshmallow ValidationError时,响应只是我的原始请求正文,而不是棉花糖错误消息。我已经进行了一些调试,并且知道正在调用错误处理程序,并且ValidationError的属性是可访问的(例如,验证error.messages{'age': ['Missing data for required field.']})。

有人曾经经历过吗?感谢您的阅读,并提前感谢您的帮助!

有效载荷:

{"name": "Bob"}

错误处理程序:

from marshmallow.exceptions import ValidationError

@api.errorhandler(ValidationError)
def marshmallow_error_handler(error):
    # print(error.messages) results in expected {'age': ['Missing data for required field.']}
    return error.messages, 400

架构:

class SimpleSchema(Schema):
    name = fields.String(required=True)
    age = fields.String(required=True)

通往测试处理程序的简单途径:

@api.route("/test")
class MarshmallowTest(Resource):
    def post(self):
        SimpleSchema().load(api.payload)

预期的响应:

{'age': ['Missing data for required field.']}

实际回答:

{"name": "Bob"}

我已经能够通过重写marshmallow.Schema的{​​{1}}函数并引发自定义异常来解决此问题,但是我仍然很奇怪是什么导致了这种行为!

1 个答案:

答案 0 :(得分:1)

我也遇到了这个错误并发现了这个 Github 问题 https://github.com/noirbizarre/flask-restplus/issues/530

我采用的解决方法是在我自己的处理程序中覆盖异常的 RecipeIngredients = Table('recipe_ingredients', Base.metadata, Column('recipe_id', Integer, ForeignKey('recipes.id')), Column('ingredient_id', Integer, ForeignKey('ingredients.id')), Column('ingredient_amount', Integer) ) class Recipe(Base): __tablename__ = 'recipes' id = Column(Integer, Sequence('recipe_id_seq'), primary_key=True, autoincrement=True) amountofpeople = Column(Integer) name = Column(String) recipe_ingredients = relationship(Ingredient, secondary=RecipeIngredients, backref=backref('recipes', lazy='dynamic')) ingredientamount = RecipeIngredients.columns.ingredient_amount 属性

data