模型验证器谷歌应用引擎 - BadValueError

时间:2015-07-24 11:38:56

标签: python google-app-engine

我从谷歌应用引擎和验证器获得ndb模型。但是当我使用邮递员尝试验证并从邮递员生成的字符串强制执行int时。我仍然得到BadValueError:BadValueError: Expected integer, got u'2'

出了什么问题?

def int_validator(prop, val):
    if val:
        val = int(val)
        return val

class TwitterUser(ndb.Model):
    """Model for twitter users"""
    screen_name = ndb.StringProperty(required=True)
    followers_count = ndb.IntegerProperty(validator=int_validator)

1 个答案:

答案 0 :(得分:1)

ndb.IntegerProperty' _validate()方法will run before your custom validator因此引发了异常。

要让您的代码正常工作,您需要使用ndb.Property代替ndb.IntegerProperty或继承_validate()并覆盖其def int_validator(prop, val): if val: val = int(val) return val class TwitterUser(ndb.Model): """Model for twitter users""" screen_name = ndb.StringProperty(required=True) followers_count = ndb.Property(validator=int_validator) 方法。

第一个解决方案看起来像这样:

class CustomIntegerProperty(ndb.IntegerProperty):
    def _validate(self, value):
        if val:
            val = int(val)
            return val
        # you still need to return something here or raise an exception

class TwitterUser(ndb.Model):
    """Model for twitter users"""
    screen_name = ndb.StringProperty(required=True)
    followers_count = ndb.CustomIntegerProperty()

第二个是这样的:

int

我认为两者都不是理想的解决方案,因为您可能更好地确保您将BadValueError传递给followers_count属性并且body以及以防万一。{1}}。

相关问题