在棉花糖中验证列表

Validate list in marshmallow

目前我正在使用棉花糖模式来验证请求, 我有一个列表,我需要验证它的内容。

class PostValidationSchema(Schema):
    checks = fields.List(
        fields.String(required=True)
    )

检查字段是一个列表,它应该只包含这些特定值["booking", "reservation", "flight"]

如果您要检查列表中是否只有这三个元素,请使用 Equal 验证器。

from marshmallow import Schema, fields, validate


class PostValidationSchema(Schema):
    checks = fields.List(
        fields.String(required=True),
        validate=validate.Equal(["booking", "reservation", "flight"])
    )

schema = PostValidationSchema()

schema.load({"checks": ["booking", "reservation", "flight"]})  # OK
schema.load({"checks": ["booking", "reservation"]})  # ValidationError

如果列表可以包含任意数量的元素,并且这些元素只能是这三个特定值之一,则使用 OneOf 验证器。

from marshmallow import Schema, fields, validate


class PostValidationSchema(Schema):
    checks = fields.List(
        fields.String(
            required=True,
            validate=validate.OneOf(["booking", "reservation", "flight"])
        ),
    )

schema = PostValidationSchema()

schema.load({"checks": ["booking", "reservation", "flight"]})  # OK
schema.load({"checks": ["booking", "reservation"]})  # OK
schema.load({"checks": ["booking", "dummy"]})  # ValidationError

除了杰罗姆的回答,我还发现如果你需要做一些需要更多逻辑的事情,你可以这样做:

def validate_check(check: str):
  return check in ["booking", "reservation", "flight"]

class PostValidationSchema(Schema):
    checks = fields.List(
        fields.String(required=True, validate=validate_check)
    )

或使用 lambda:

class PostValidationSchema(Schema):
    checks = fields.List(
        fields.String(required=True, validate=lambda check: check in ["booking", "reservation", "flight"])
    )