【发布时间】:2013-01-21 14:56:12
【问题描述】:
我在 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 块中的 pass。
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 中创建表单时,我该怎么做才能避免这个错误呢?
【问题讨论】:
-
我不明白
'Sök'.decode('utf-8')的所有用法。为什么不首先使用 Unicode:u'Sök'? -
@DanielRoseman 使用 uString 也可以,但不能解决问题。
-
不,我没有说它会(这就是为什么我将其发布为评论,而不是答案)。但是,您确实需要显示正确的回溯,因为错误显然不是由
pass语句引起的。 -
@manu-fatto 我编辑了帖子,谢谢。
-
@DanielRoseman 添加了完整的回溯。
标签: python unicode utf-8 web.py