2010-09-27 89 views
0

我想創建一個識別IDN的驗證碼驗證程序以在我的一個項目中使用。我使用了Django項目中的一部分代碼(http://code.djangoproject.com/svn/django/trunk/django/core/validators.py)來做到這一點,但是我的代碼中必須有一個微不足道的錯誤I找不到:電子郵件驗證碼驗證程序出錯

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域名(例如:[email protected]ääl.de)的電子郵件後,第一個電話提出的無效拋出異常,以及代碼之後的部分第一個除外從不執行('heywo!'從不打印)。

有一個例子:

>>> from test.lib.validators import Email 
>>> Email().to_python(u'[email protected]ää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) 

我做了什麼錯?

謝謝。

+0

請編輯文章,包括你的錯誤得到堆棧跟蹤。 – Daenyth 2010-09-28 00:05:47

+0

我加了痕跡。正如我所說,這只是我期望通過調用_original_ Email驗證程序的結果。事實並非如此:/ – Pierre 2010-09-28 00:14:09

+0

我會在跟蹤報告的validators.py中查看第1352行。我懷疑是誰讓這個模塊不能正確處理unicode域部分。我也不完全確定他們是有效的,但他們可能很容易(我沒有足夠的知識)。它是否會在您刪除unicode時進行驗證? – Daenyth 2010-09-28 00:20:49

回答

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 

它的工作完美:)

+0

你應該將'raise e'行改爲'raise'。如果這樣做,它將保留堆棧跟蹤而不是重寫它。 – Daenyth 2010-09-28 14:01:48

+0

我會做。謝謝。 – Pierre 2010-09-28 15:45:42