【问题标题】:marshmallow schema validation dash problem棉花糖模式验证破折号问题
【发布时间】:2021-06-11 13:03:31
【问题描述】:

我正在使用棉花糖来验证架构的某些字段。

class PlantDetailsSchema(Schema):
        name: fields.Str(required=True, validate=validate.Length(min=3)),
        sprout-time: fields.Str(required=True, validate=validate.Length(min=3)),
        full-growth: fields.Str(required=True, validate=validate.Length(min=5)),
        edible: fields.Bool(required=True)



class PlantInfoSchema(Schema):
    plant = fields.Nested(PlantDetailsSchema)
    num = fields.Int(required=True, validate=validate.Range(min=1))


def validate_json(json):
    try:
        schema = PlantInfoSchema().load(json)
        ret = schema.dump()
        return ret
    except ValidationError:
        return None

要验证的 json 元素是: json = {'植物':{'名称':'盆景','发芽时间':'3个月','完全生长':'2年','可食用':False},'num':3 }

我的问题是如何验证名称中间包含破折号的字段(如“sprout-time”和“full-growth”。您有解决此问题的想法吗?

【问题讨论】:

    标签: json validation marshmallow


    【解决方案1】:

    您可以使用“data_key”属性来指定带有破折号的键名。将字段名称定义为有效的名称,例如“sprout_time”(可以是任何名称),并将 data_key 定义为实际名称为“sprout-time”的字段的属性。

    class PlantDetailsSchema(Schema):
        name = fields.Str(required=True, validate=validate.Length(min=3))
        sprout_time = fields.Str(
            data_key='sprout-time',
            required=True, validate=validate.Length(min=3)
        )
        full_growth = fields.Str(
            data_key='full-growth',
            required=True, 
            validate=validate.Length(min=5)
        )
        edible = fields.Bool(required=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多