gpt4 book ai didi

python - formencode Schema 动态添加字段

转载 作者:太空狗 更新时间:2023-10-30 02:34:42 24 4
gpt4 key购买 nike

例如,我们以一个用户 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 docs :

Validators use instance variables to store their customization information. You can use either subclassing or normal instantiation to set these.

Schema 在文档中被称为复合验证器,并且是 FancyValidator 的子类,所以我猜它是正确的。

但这不起作用:简单添加的 phone_n 将被忽略,只需要 name

更新:

我也尝试过重写 __new____classinit__ 在询问之前没有成功...

最佳答案

我遇到了同样的问题,我在这里找到了解决方案: http://markmail.org/message/m5ckyaml36eg2w3m

所有的事情就是在你的init方法中使用schema的add_field方法

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)
self.add_field(key, validators.PhoneNumber(not_empty=True))

我认为没有必要调用父初始化

关于python - formencode Schema 动态添加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6773957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com