python marshmallow force field.int 只接受 int 而不是字符串

标签 python int marshmallow

我有一个棉花糖整数字段,但是当我传递数据时很奇怪 因为 {number:"123"} 也可以工作,就好像是一个整数,我会假设内部正在转换为 int,但不希望我想强制用户一直使用 INT 所以有不要混淆哪些数据类型可以接受,是否有方法或参数?

number = fields.Integer(required=True,
                        validate=Range(min=1, error="Value must be greater than 0"))

谢谢大家的帮助。

最佳答案

查看the code我认为这是不可能的,我对此感到惊讶。我知道您可以设置一个strict 标志,但它只在某些情况下起作用。观察:

from marshmallow import *
from  marshmallow.validate import Range

class MySchema(Schema):
    number = fields.Integer(strict=True, required=True, validate=[Range(min=1, error="Value must be greater than 0")])

在这种情况下有效:

s = MySchema()
s.dumps({'number': "123.1"})
>>> MarshalResult(data='{}', errors={'number': ['Not a valid integer.']})

但在这些情况下不是

s.dumps({'number': 123.1})
>>> MarshalResult(data='{"number": 123}', errors={})

s.dumps({'number': "123"})
>>> MarshalResult(data='{"number": 123}', errors={})

我觉得这不一致。也许你最好的选择是写一个 custom field或在将输入传递给您的模式之前验证输入的不同验证器。

更新: 看起来这个问题在最新版本的 Marshmallow 中得到了修复

关于python marshmallow force field.int 只接受 int 而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50142866/

相关文章:

c - sscanf 似乎在 uint 变量和 c 中的 int 变量上表现不同

c#计算数组内的整数

python - 使用 Cairo 绘制一个固定的均匀三次 B 样条曲线

python - 如何在 Process() 中中断 Queue.get()?

python - 在 Tensorflow 中过滤数据

c - 你好.c : In function ‘main’ : Hello. c :13: warning: return type of ‘main’ is not ‘int’ ?

python - 基于Flask的REST API : marshmallow vs flask-restful

flask - 处理可选的字段验证

sqlalchemy - 如何将 marshmallow-sqlalchemy 与异步代码一起使用?

python - "math.floor(x)"和 "int(x)"是否在 Python 中对正实数产生不同的结果?