Python UnicodeDecodeError的最佳做法 [英] Best Practices for Python UnicodeDecodeError
问题描述
我使用基于Web的应用程序的 Pylons 框架, Mako 模板。 Python处理unicode字符串的方式并不困难,当我看到我的网站崩溃时,我已经紧张的时刻,当页面被渲染后,我后来才知道它与 UnicodeDecodeError 。
I use Pylons framework, Mako template for a web based application. I wasn't really bother too deep into the way Python handles the unicode strings. I had tense moment when I did see my site crash when the page is rendered and later I came to know that it was related to UnicodeDecodeError.
看到错误后,我开始围绕我的Python代码添加编码,解码使用'ignore'选项的字符串调用,但仍然看不到错误有时候。
After seeing the error, I started mesh around my Python code adding encode, decode calls for string with 'ignore' option but still I could not see the errors gone sometime.
最后,我用来忽略ascii解码,使网站运行没有任何崩溃。
Finally I used to decode to ascii with ignore and made the site running without any crash.
输入到我的网站通过许多网站。这意味着我不会控制选择的语言或语言。我的网站支持国际语言和英语。我有一个feed汇编,一般不用麻烦unicode / ascii / utf-8。当我通过mako模板显示文本时,我显示为原样。
Input to my site comes through many sites. This means that I do not control the languages or language of choice. My site supports international languages and along with English. I have feed aggregation which generally not bother about unicode/ascii/utf-8. While I display the text through mako template, I display as it is.
不是网络专家,在Python项目中处理字符串的最佳做法是什么?我应该只在渲染文本时关心或应用程序的所有阶段?
Not being a web expert, what are the best practices to handle the strings within the Python project? Should I care only while rendering the text or all the phase of the application?
推荐答案
如果您有影响,这是无痛的方式:
If you have influence on it, this is the painless way:
- 尽快知道您的输入编码(或忽略解码)和
decode(encoding)
因为它触及你的应用程序 - 内部仅使用unicode(
u'something'
是unicode),也在数据库中 - 用于渲染,导出等,随时离开您的应用程序,
encode('utf-8')
数据
- know your input encoding (or decode with ignore) and
decode(encoding)
the data as soon as it hits your app - work internally only with unicode (
u'something'
is unicode), also in the database - for rendering, export etc, anytime it leaves your app,
encode('utf-8')
the data
这篇关于Python UnicodeDecodeError的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!