gpt4 book ai didi

python - 自动剥离()WTForms中的所有值?

转载 作者:太空狗 更新时间:2023-10-29 18:01:30 24 4
gpt4 key购买 nike

有没有办法在不向每个字段添加过滤器的情况下从 WTForms 中的所有值中去除周围的空白?

目前我正在将 filters=[strip_whitespace] 和下面显示的函数传递给我的字段,但必须为每个字段重复此操作非常难看。

def strip_whitespace(s):
if isinstance(s, basestring):
s = s.strip()
return s

需要对 Form 进行子类化的解决方案会很好,因为我已经在我的应用程序中这样做了。

最佳答案

您可以使用 bind_field 在 WTForms 2.x 中执行此操作class Meta 上的原语。 class Meta paradigm 是一种在绑定(bind)/实例化字段、呈现字段等上下文中覆盖 WTForms 行为的方法。

因为在表单上定义的 class Meta 中覆盖的任何内容都会继承到任何表单子(monad)类,您可以使用它来设置具有所需行为的基表单类:

class MyBaseForm(Form):
class Meta:
def bind_field(self, form, unbound_field, options):
filters = unbound_field.kwargs.get('filters', [])
filters.append(my_strip_filter)
return unbound_field.bind(form=form, filters=filters, **options)


def my_strip_filter(value):
if value is not None and hasattr(value, 'strip'):
return value.strip()
return value

现在,只需为所有表单继承 MyBaseForm 即可。

关于python - 自动剥离()WTForms中的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26232165/

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