formencode Schema动态添加字段
让我们以一个用户Schema
为例,其中网站管理员设置请求的电话号码的数量:
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 文档:
验证器使用实例变量来存储其自定义内容 信息。您可以使用子类化或普通实例化来 设置这些。
并且 Schema
在文档中被称为复合验证器,并且是 FancyValidator
的子类,所以我猜它是正确的。
但这不起作用:简单添加的 phone_n
会被忽略,只需要 name
。
更新:
我还尝试了覆盖 __new__
和 __classinit__
在询问之前没有成功......
Let's take, for example, a User Schema
where the site admin sets the number of requested phone numbers:
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)
...
Somehow I thought I could simply do:
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)
since I read in FormEncode docs:
Validators use instance variables to store their customization
information. You can use either subclassing or normal instantiation to
set these.
and Schema
is called in docs as a Compound Validator and is a subclass of FancyValidator
so I guessed it's correct.
But this does not work: simply added phone_n
are ignored and only name
is required.
Update:
Also I tried both overriding __new__
and __classinit__
before asking with no success...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我遇到了同样的问题,我在这里找到了解决方案:
http://markmail.org/message/m5ckyaml36eg2w3m
所有的事情都是使用 schema 的 add_field 方法你是 init 方法,
我认为不需要调用父 init
i had the same problem, i found a solution here:
http://markmail.org/message/m5ckyaml36eg2w3m
all the thing is to use the add_field method of schema in youre init method
i don't think there's a need to call the parent init