web.py Form.validates()错误,属性名称中包含utf-8字符

时间:2013-01-21 14:56:13

标签: python unicode utf-8 web.py

我在web.py中有一个表单,感谢string.decode('utf-8'),但是当它提交时,我在attrget第17行的web / form.py中得到'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128)

该代码如下所示,第17行特别是except块中的传递。

def attrget(obj, attr, value=None):
    try:
        if hasattr(obj, 'has_key') and obj.has_key(attr): 
            return obj[attr]
    except TypeError:
        # Handle the case where has_key takes different number of arguments.
        # This is the case with Model objects on appengine. See #134
        pass
    if hasattr(obj, attr):
        return getattr(obj, attr)
    return value

它必须是关于编码的东西,因为如果我删除瑞典语字符,表单是有效的。这是表单定义。

searchForm = form.Form(
    form.Textbox('Startdatum', id='datepickerStart'),
    form.Textbox('Slutdatum', id='datepickerEnd'),
    form.Textbox('IPadress', validIPaddress),
    form.Textbox('Macadress', validMacaddress),
    form.Button('Sök'.decode('utf-8'), type='submit', description='Search')
)

调用Form.validates()的第三行是触发它的位置。

def POST(self):
    form = self.searchForm()
    if not form.validates():
        headerMsg = 'Du skrev något fel, gör om, gör rätt.'.decode('utf-8')
        return tpl.index(headerMsg, form)

    return tpl.index(headerMsg='Inga rader hittades', form=form)

完整的追溯如下。

Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/application.py", line 239, in process
return self.handle()
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/application.py", line 230, in handle
    return self._delegate(fn, self.fvars, args)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/application.py", line 420, in _delegate
    return handle_class(cls)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/application.py", line 396, in handle_class
    return tocall(*args)
  File "/home/mkbnetadm/netadmin/na.py", line 36, in POST
    if not form.validates():
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/form.py", line 76, in validates
    v = attrget(source, i.name)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.37-py2.6.egg/web/form.py", line 18, in attrget
    if hasattr(obj, attr):
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128)

那么在web.py中创建表单时,我该怎么做才能避免此错误?

1 个答案:

答案 0 :(得分:0)

与所有标识符一样,属性名称必须(可转换为)ASCII:

[Python 2.6.6]
>>> foo = object()
>>> hasattr(foo, 'o')
False
>>> hasattr(foo, u'o')
False
>>> hasattr(foo, u'\xf6')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
>>>

请参阅http://docs.python.org/2/reference/lexical_analysis.html#identifiers