3
让我们举个例子,一个用户Schema
在站点管理员设置要求的电话号码数量:formencode架构字段添加动态
class MySchema(Schema):
name = validators.String(not_empty=True)
phone_1 = validators.PhoneNumber(not_empty=True)
phone_2 = validators.PhoneNumber(not_empty=True)
phone_3 = validators.PhoneNumber(not_empty=True)
...
不知怎的,我以为我可以简单地做:
class MySchema(Schema):
name = validators.String(not_empty=True)
def __init__(self, *args, **kwargs):
requested_phone_numbers = Session.query(...).scalar()
for n in xrange(requested_phone_numbers):
key = 'phone_{0}'.format(n)
kwargs[key] = validators.PhoneNumber(not_empty=True)
Schema.__init__(self, *args, **kwargs)
因为我在FormEncode docs中读到:
验证器使用实例变量来存储他们的customiza信息 信息。您可以使用子类化或正常实例化来设置这些。
和Schema
被称为文档作为复合验证,是FancyValidator
子类,所以我猜它是正确的。
但这不起作用:只需添加phone_n
就会被忽略,只需要name
。
更新:
此外,我都尝试重写__new__
和__classinit__
没有成功前问...
是的!谢谢!经过一个多小时寻找解决方案后,这才解决了我的问题。 – Brodan