2011-09-12 51 views
2

我正在嘗試讀取數據庫表內容並使用makobottle將其顯示爲網頁。該表中有一些Unicode(utf-8)字段。Python + mako Unicode問題

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) 

如何去aboutthis?我已經試過:

return tmpl.render_unicode(**kwds)` 

return tmpl.render_unicode(**kwds).encode('utf-8', 'replace') 

,沒有運氣,而this answer沒有太大幫助。

任何想法?

回答

1

問題不在於render_unicode無法將python unicode對象轉換爲utf8,它存在字符串對象,它假定爲ascii,並且不包含ascii數據。

從頭開始 - 內部所有傳入的字符串解碼成Unicode。你有一個需要修復的字符串輸入。

我建議你嘗試命名在邊界的所有變量帶有幾分匈牙利命名法 - 也許rawstr_myvar和u_myvar。