python - 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.']}
但它们都不适用于两种类型。有没有办法接受两种类型:字符串和整数?
解决方案
Marshmallow(fields.Number
从中fields.Integer
,fields.Float
和field.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
处理您的数据。
推荐阅读
- php - 如何传递类别 ID 以形成帖子
- regex - 在 Perl 中的某个特定匹配项下方编辑/匹配字符串 n 行?
- haskell - 块缩进会导致错误吗?
- html - Sticky footer with background image
- python - 如何从scala中的avro文件中读取元数据
- html - How do I stack two rows on top of each other using Bootstrap?
- sparql - Virtuoso SPARQL Bug 与 BIND
- c# - 如何在 Azure Function 中定义“外部”StorageAccount?
- php - How to setup an existing php project which used composer in a localhost with xampp?
- css - How to make table width auto with d3.js