Question

Je voulais créer un formencode IDN au courant validateur à utiliser dans l'un de mes projets. J'ai utilisé une partie de code du projet Django (http://code.djangoproject.com/svn/django/trunk/django/core/validators.py) pour le faire, mais il doit y avoir une erreur dans mon code trivial I ne peut pas trouver:

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

Lorsque je tente de valider un e-mail avec un domaine IDN (ex: test@wääl.de), l'exception non valide soulevée par le premier appel est lancé, et la partie du code après la première exception est jamais exécuté ( 'heywo ! n'est jamais imprimé).

Il est un exemple:

>>> 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)

Qu'est-ce que je fait de mal?

Merci.

Était-ce utile?

La solution

D'accord, trouvé la réponse. Je surchargeait _to_python au lieu de validate_python. La classe ressemble maintenant à:

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

Il fonctionne parfaitement:)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top