FormEncode 验证:单词除以逗号

发布于 2024-09-27 10:39:46 字数 126 浏览 3 评论 0原文

如何通过 FormEncode 验证用逗号分隔的单词?

像这样的事情:

"foo1, foo2, foo3" -> ["foo1", "foo2", "foo3"]

How to validate words divided by a comma by FormEncode ?

Something like this:

"foo1, foo2, foo3" -> ["foo1", "foo2", "foo3"]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

染年凉城似染瑾 2024-10-04 10:39:46

您可能需要一个自定义验证器。这是一个简单的示例:

import formencode

class CommaSepList(formencode.validators.FancyValidator):

    def _to_python(self, value, state):
        return value.split(",")

    def validate_python(self, value, state):
        for elem in value:
            if elem == "": 
                raise formencode.Invalid("an element of the list is empty", value, state) 

>>> CommaSepList.to_python("1,2,3")
['1', '2', '3']
>>> CommaSepList.to_python("1,,")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.5/site-packages/FormEncode-1.2.3dev-py2.5.egg/formencode/api.py", line 416, in to_python
    vp(value, state)
  File "myValidator.py", line 17, in validate_python
    raise formencode.Invalid("an element of the list is empty", value, state)

当然,您需要添加特定于您的用例的验证。

You'll probably need a custom validator. Here's a quick example:

import formencode

class CommaSepList(formencode.validators.FancyValidator):

    def _to_python(self, value, state):
        return value.split(",")

    def validate_python(self, value, state):
        for elem in value:
            if elem == "": 
                raise formencode.Invalid("an element of the list is empty", value, state) 

>>> CommaSepList.to_python("1,2,3")
['1', '2', '3']
>>> CommaSepList.to_python("1,,")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.5/site-packages/FormEncode-1.2.3dev-py2.5.egg/formencode/api.py", line 416, in to_python
    vp(value, state)
  File "myValidator.py", line 17, in validate_python
    raise formencode.Invalid("an element of the list is empty", value, state)

Of course, you'll want to add validation specific to your use case.

橙幽之幻 2024-10-04 10:39:46

假设每个单词都用逗号和空格分隔 (', '):

>>> x = "foo1, bar2, foo3"
>>> x.split(', ')
['foo1', 'bar2', 'foo3']

然后将该列表传递给 FormEncode 并让它执行您需要执行的操作。

Assuming each word is separated by a comma and a space (', '):

>>> x = "foo1, bar2, foo3"
>>> x.split(', ')
['foo1', 'bar2', 'foo3']

And then pass that list on to FormEncode and have it do whatever you need it to do.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文