0

我想创建一个可识别 IDN 的 formencode 验证器以在我的一个项目中使用。我使用了 Django 项目 (http://code.djangoproject.com/svn/django/trunk/django/core/validators.py) 中的一部分代码来做到这一点,但我的代码中肯定有一个小错误找不到:

class Email(formencode.validators.Email):
    def _to_python(self, value, state):
        try:
            return super(Email, self)._to_python(value, state)
        except formencode.Invalid as e:
            # Trivial case failed. Try for possible IDN domain-part

            print 'heywo !'

            if value and u'@' in value:
                parts = value.split(u'@')
                try:
                    parts[-1] = parts[-1].encode('idna')
                except UnicodeError:
                    raise e

                try:
                    super(Email, self)._to_python(u'@'.join(parts), state)
                except formencode.Invalid as ex:
                    raise ex

                return value
            else:
                raise e

当我尝试使用 IDN 域(例如:test@wääl.de)验证电子邮件时,第一次调用引发的 Invalid 异常被抛出,并且第一个 except 之后的代码部分永远不会执行('heywo!'是从未印刷)。

有一个例子:

>>> from test.lib.validators import Email
>>> Email().to_python(u'test@zääz.de')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/FormEncode-1.2.3dev-py2.6.egg/formencode    /api.py", line 416, in to_python
    vp(value, state)
  File "/usr/local/lib/python2.6/dist-packages/FormEncode-1.2.3dev-py2.6.egg/formencode    /validators.py", line 1352, in validate_python
    value, state)
Invalid: The domain portion of the email address is invalid (the portion after the @: z\xe4\xe4z.de)

我做错了什么 ?

谢谢。

4

1 回答 1

0

好的,找到答案了。我正在重载_to_python而不是validate_python. 该类现在看起来像:

class Email(formencode.validators.Email):
    def validate_python(self, value, state):
        try:
            super(Email, self).validate_python(value, state)
        except formencode.Invalid as e:
            # Trivial case failed. Try for possible IDN domain-part
            if value and u'@' in value:
                parts = value.split(u'@')
                try:
                    parts[-1] = parts[-1].encode('idna')
                except UnicodeError:
                    raise e

                try:
                    super(Email, self).validate_python(u'@'.join(parts), state)
                except formencode.Invalid as ex:
                    raise ex
            else:
                raise e

它工作得很好:)

于 2010-09-28T09:19:47.093 回答