gpt4 book ai didi

python - 有序 = True 不受尊重。 python +棉花糖+ flask

转载 作者:行者123 更新时间:2023-12-03 23:39:20 25 4
gpt4 key购买 nike

又是我,现在有一个棉花糖问题,我有以下结构:
路线.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 类上的属性 orders=True 不起作用
我一直在一些帖子中寻找它,看起来当您混合嵌套字段和有序属性时会出现问题。
这是我的堆栈
flask-marshmallow==0.14.0
marshmallow==2.21.0
marshmallow-sqlalchemy==0.23.1

最佳答案

我看到您可以尝试两种不同的策略:
在应用程序定义之后将此配置行添加到您的代码中:

app = Flask (__ name__)
app.config ['JSON_SORT_KEYS'] = False
抑制 flask 字典键排序并强制遵守定义的顺序。
您也可以尝试在 ParentSchema 类中添加用于排序键的相同元数据,因为 ChildSchema 包含在 ParentSchema 中;我们也需要指定 ParentSchema 以尊重键顺序。
就像是
class ParentSchema(Schema):
class Meta:
ordered = True

response = fields.Nested(ChildSchema)
我希望你觉得这有用,问候

关于python - 有序 = True 不受尊重。 python +棉花糖+ flask ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66806842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com