Python+mako Unicode 问题
我正在尝试读取一个数据库表的内容,并使用 mako
和 bottle
将其显示为网页。这个表里有一些Unicode(utf-8)字段。
UnicodeDecodeError('ascii', 'MOTOROLA MILESTONE\xe2\x84\xa2 PLUS',
18, 19, 'ordinal not in range(128)')
出现了以下错误信息:
Traceback (most recent call last):
File "/workspace/web/controller/bottle.py", line 499, in handle
return handler(**args)
File "webserver/webserver.py", line 101, in download
return html_tmpl(tmpl, **kwds)
File "webserver/webserver.py", line 116, in html_tmpl
return tmpl.render(**kwds)
File "/usr/lib/python2.5/site-packages/Mako-0.3.4-py2.5.egg/mako/template.py", line 189, in render
return runtime._render(self, self.callable_, args, data)
File "/usr/lib/python2.5/site-packages/Mako-0.3.4-py2.5.egg/mako/runtime.py", line 403, in _render
_render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data))
File "/usr/lib/python2.5/site-packages/Mako-0.3.4-py2.5.egg/mako/runtime.py", line 434, in _render_context
_exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
File "/usr/lib/python2.5/site-packages/Mako-0.3.4-py2.5.egg/mako/runtime.py", line 457, in _exec_template
callable_(context, *args, **kwargs)
File "download_android_index_html", line 41, in render_body
File "download_android_index_html", line 23, in fill_devices
File "download_android_index_html", line 68, in render_fill_devices
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 18: ordinal not in range(128)
调用这个函数的地方是:
def html_tmpl(tmpl, **kwds):
kwds['nav'] = templates_lookup.get_template('nav.html').render()
kwds['nav_bottom'] = templates_lookup.get_template('nav_bottom.html').render()
base_path = request.path.replace("de/","").replace("fr/","")
kwds['languages'] = templates_lookup.get_template('languages.html').render(en_url=base_path,fr_url="/fr"+base_path)
kwds['analytics'] = ''
return tmpl.render(**kwds)
我该怎么做呢?我尝试过:
return tmpl.render_unicode(**kwds)`
还有
return tmpl.render_unicode(**kwds).encode('utf-8', 'replace')
但都没有成功,另外 这个回答也没什么帮助。
有没有什么好的建议?
1 个回答
1
问题不是说render_unicode不能把Python的unicode对象转换成utf8,而是有一个字符串对象,它被认为是ascii格式,但实际上里面包含了非ascii的数据。
从头开始吧——把所有传入的字符串都转换成unicode格式。你有一个需要修正的字符串输入。
我建议你在边界处给所有变量起个名字,使用一种类似匈牙利命名法的方式——比如可以用rawstr_myvar和u_myvar这样的命名。