首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python+mako Unicode问题

Python+mako Unicode问题
EN

Stack Overflow用户
提问于 2011-09-12 23:02:57
回答 1查看 916关注 0票数 2

我正在尝试读取DB表的内容,并使用makobottle将其显示为网页。该表中包含一些Unicode (utf-8)字段。

代码语言:javascript
复制
UnicodeDecodeError('ascii', 'MOTOROLA MILESTONE\xe2\x84\xa2 PLUS', 
                   18, 19, 'ordinal not in range(128)')

使用以下堆栈跟踪:

代码语言:javascript
复制
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)

调用函数为:

代码语言:javascript
复制
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)

我该怎么做呢?我试过了:

代码语言:javascript
复制
return tmpl.render_unicode(**kwds)` 

代码语言:javascript
复制
return tmpl.render_unicode(**kwds).encode('utf-8', 'replace')

运气不佳,this answer也帮不了什么忙。

有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-09-13 02:58:40

问题不在于render_unicode不能将python unicode对象转换为utf8,而在于字符串对象存在,它假定该对象为ascii,并且保存非ascii数据。

从头开始-在内部将所有传入的字符串解码为unicode。您有一个需要修复的字符串输入。

我建议您尝试使用一种匈牙利符号来命名边界上的所有变量-也许是rawstr_myvar和u_myvar。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7389935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档