5

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.

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.

Finally I used to decode to ascii with ignore and made the site running without any crash.

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.

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?

4

2 回答 2

11

如果你对它有影响,这是无痛的方式:

  • 知道您的输入编码(或忽略解码)和decode(encoding)数据,一旦它到达您的应用程序
  • 仅在内部使用 unicode ( u'something'is unicode),也在数据库中工作
  • 用于渲染、导出等,只要它离开您的应用程序,encode('utf-8')数据
于 2010-10-14T14:01:58.773 回答
2

这对您来说可能不是一个可行的选择,但是让我说,在使用 python 3 时,大量与编码相关的错误消失了,只是因为 unicode 字符串和字节对象之间的分离变得更加清晰。当我必须使用 python 2 时,我选择 2.6 版本,您可以在其中声明from future import unicode_literals. 不信的人实际上应该阅读您发布的链接,因为它指出了 Python 的编码/解码行为的一些微妙之处,幸运的是在 Python 3 中消失了。

你说

我不控制语言或选择的语言。我的网站支持国际语言和英语。我有提要聚合,通常不关心 unicode/ascii/utf-8

好吧,无论您选择做什么,很明显您不希望您的 Web 应用程序崩溃,因为您使用的某些 dænish bløgger 的提要选择以一种不起眼的斯堪的纳维亚编码方案对他们的帖子进行编码。根本问题与所有 Web 应用程序有关,因为 URL 不携带编码信息,而且您永远不知道恶意用户可能想要发送给您的字节序列。在这种情况下,我执行我所说的“安全链解码”:我首先尝试解码为 utf-8,如果失败,请使用 cp1252 重试。如果失败,我会丢弃请求(HTTP 404)或类似的东西。

你提到你处理提要和¿你?¿提要?不要“打扰” unicode 和编码。你能澄清一下这个说法吗?它完全避开了我如何成功地构建一个包含多种语言文本而不关心编码的站点。显然使用 ascii-only 不会让你走得太远。

于 2010-10-14T15:04:10.480 回答