gpt4 book ai didi

python - 是否可以使用棉花糖验证列表?

转载 作者:太空狗 更新时间:2023-10-29 20:39:26 26 4
gpt4 key购买 nike

是否可以使用 marshmallow 验证列表?

class SimpleListInput(Schema):
items = fields.List(fields.String(), required=True)

# expected invalid type error
data, errors = SimpleListInput().load({'some': 'value'})

# should be ok
data, errors = SimpleListInput().load(['some', 'value'])

或者只验证对象?

最佳答案

要验证顶级列表,您需要使用 many=True 参数实例化您的列表项架构。

例子:

class UserSchema(marshmallow.Schema):
name = marshmallow.fields.String()

data, errors = UserSchema(many=True).load([
{'name': 'John Doe'},
{'name': 'Jane Doe'}
])

但它仍然需要是一个对象模式,Marshmallow 不支持使用顶级非对象列表。如果您需要验证非对象类型的顶级列表,一种解决方法是使用您的类型的一个 List 字段定义一个模式,并将有效负载包装成一个对象:

class SimpleListInput(marshmallow.Schema):
items = marshmallow.fields.List(marshmallow.fields.String(), required=True)

payload = ['foo', 'bar']
data, errors = SimpleListInput().load({'items': payload})

关于python - 是否可以使用棉花糖验证列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37237350/

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