Email formencode验证器出错

时间:2010-09-27 23:46:54

标签: python formencode

我想在我的一个项目中创建一个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),第一次调用引发的无效异常将被抛出,而第一次调用之后的代码部分将永远不会被执行('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)

我做错了什么?

感谢。

1 个答案:

答案 0 :(得分: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

它完美地运作:)