【问题标题】:Marshmallow: why can't I access the fields attributes?棉花糖:为什么我不能访问字段属性?
【发布时间】:2020-11-10 22:12:55
【问题描述】:

我有一个非常常规的模式类,例如:

class TestSchema(db_schema.SQLAlchemyAutoSchema):
    xxx = fields.Str()
    name = fields.Str(validate=validate.Length(min=1), required=True, error_messages={"required": "The name is required."})
    class Meta:
        fields = ('id', 'name', 'description')
        model = TestModel

我想分析类本身,以便能够为前端形成一些元信息。但我无法访问 xxx 或类似的名称:

schema_instance = TestSchema()
schema_instance.xxx ???AttributeError: 'TestSchema' object has no attribute 'xxx'

【问题讨论】:

  • 您需要另一个类并将其转储到TestSchema,然后它将起作用

标签: python marshmallow flask-marshmallow


【解决方案1】:

作为@maruthi-adithya cmets,您需要定义另一个类来转储TestSchema的结果;您需要使用postload 处理后反序列化,您可以在其中根据需要返回数据,请查看here 的文档。下面是一个例子:

class Test:
    def __init__(self, xxx, name, id):
        self.xxx = xxx
        self.name = name
        self.id = id
    def __repr__(self):
        return (
            f'<Test(xxx={self.id}, name={self.name})'
        )


class TestSchema(db_schema.SQLAlchemyAutoSchema):
    xxx = fields.Str()
    name = fields.Str(validate=validate.Length(min=1), required=True, error_messages={"required": "The name is required."})
    id = fields.Integer()
    class Meta:
        fields = ('id', 'name', 'description')
        model = TestModel

    @postload
    def return_as_object(self, data, **kwargs):
        return Test(**data)

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2016-03-15
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多