【问题标题】:ordered = True not respected. python + marshmallow + Flask有序 = True 不被尊重。蟒蛇+棉花糖+烧瓶
【发布时间】:2021-03-25 20:08:22
【问题描述】:

又是我,现在有一个棉花糖问题,我有以下结构:

route.py

@models.response(ParentSchema())
def get(args, model_id):

    return {"response": {"a": [{"data": "a"}], "b": [{"data": "a"}], "c": [{"data": "a"}], "d": [{"data": "a"}]}}

那么这是我的架构文件 架构.py

class SubChildSchema(Schema):
    data = fields.Str(description="Model's name")


class ChildSchema(Schema):

    class Meta:
        ordered = True

    a = fields.Nested(SubChildSchema, many=True)
    b = fields.Nested(SubChildSchema, many=True)
    c = fields.Nested(SubChildSchema, many=True)
    d = fields.Nested(SubChildSchema, many=True)


class ParentSchema(Schema):
    response = fields.Nested(ChildSchema)

假设在响应中我应该得到一个排序的响应,例如:

{
    "response": {
        "a": [
            {
                "data": "a"
            }
        ],
        "b": [
            {
                "data": "a"
            }
        ],
        "c": [
            {
                "data": "a"
            }
        ],
        "d": [
            {
                "data": "a"
            }
        ]
    }
}

但我收到的不是那个

{
    "response": {
        "b": [
            {
                "data": "a"
            }
        ],
        "c": [
            {
                "data": "a"
            }
        ],
        "d": [
            {
                "data": "a"
            }
        ],
        "a": [
            {
                "data": "a"
            }
        ]
    }
}

ChildSchema 类上的属性 ordered=True 似乎不起作用 我一直在一些帖子中寻找这个问题,看起来当您混合嵌套字段和有序属性时会出现问题。

这是我的堆栈

flask-marshmallow==0.14.0
marshmallow==2.21.0
marshmallow-sqlalchemy==0.23.1

【问题讨论】:

    标签: python marshmallow


    【解决方案1】:

    我发现您可以尝试两种不同的策略:

    在应用定义之后将此配置行添加到您的代码中:

    app = Flask (__ name__)
    app.config ['JSON_SORT_KEYS'] = False
    

    抑制烧瓶字典键排序并强制遵守定义的顺序。

    您也可以尝试在 ParentSchema 类中添加相同的元数据来排序键,因为 ChildSchema 包含在 ParentSchema 中;我们还需要指定 ParentSchema 以遵守键顺序。

    类似

    class ParentSchema(Schema):
        class Meta:
            ordered = True
    
        response = fields.Nested(ChildSchema)
    

    我希望你觉得这很有用,问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-02
      • 2019-03-04
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      相关资源
      最近更新 更多