首页 > 解决方案 > python marshmallow 取 fields.Int() 或 fields.Str()

问题描述

我从另一个源接收数据,该源有时发送一个 int,有时发送一个给定变量的字符串:位置。例如,他们将 1、2 或 3 用于整数,或者他们将发送“building”或“car”或“bus”作为示例。

我试过了

location = fields.Int(allow_string=True, strict=False)

这给出了以下错误

marshmallow.exceptions.ValidationError: {'status': ['Not a valid integer.']}

location = fields.Str(allow_int=True, strict=False)

这给出了以下错误

marshmallow.exceptions.ValidationError: {'status': ['Not a valid string.']}

但它们都不适用于两种类型。有没有办法接受两种类型:字符串和整数?

标签: pythonstringintmarshmallow

解决方案


Marshmallowfields.Number从中fields.Integerfields.Floatfield.Decimal继承)将愉快地接受有效的“可转换”字符串。

这意味着您可以选择将整数或字符串传递给它们而不会出现问题。但是,如果转换失败,您将面临异常。

class MySchema(Schema):
     foo = fields.Integer()

MySchema().load({"foo": "123"})
# prints {"foo": 123}

MySchema().load({"foo": 456})
# prints {"foo": 456}

MySchema().load({"foo": "bar"})
# marshmallow.exceptions.ValidationError: {'foo': ['Not a valid integer.']}

相反,fields.String不会接受任何整数。

class MySchema(Schema):
     foo = fields.Integer()

MySchema().load({"foo": "bar"})
# prints {"foo": "bar}

MySchema().load({"foo": 123})
# marshmallow.exceptions.ValidationError: {'foo': ['Not a valid string.']}

如果您的输入是整数或包含整数的字符串,您可以使用它fields.Integer来解析它们。

如果这是更随机的事情,您将需要使用@shihe zhang 提到的自定义字段_deserialize并自定义和_serialize处理您的数据。


推荐阅读