Hack Jinja2 to encode from `utf-8` instead of `ascii`?

≡放荡痞女 提交于 2019-12-29 08:18:23

问题


Jinja2 converts all template variables into unicode before processing. Can anybody find a place where does this happen?

The problem is that it assumes that strings are ascii, but we (at Roundup) are using utf-8 internally and our ORM (HyperDB) restores object properties to utf-8 automatically, and converting them all into unicode in every view just before passing to templates is too much legwork.


回答1:


Answer from Armin:

Unfortunately that is impossible. Jinja uses the default string coercion on 2.x that Python provides for speed. There are no guaranteed calls to make something unicode. The only shitty choice you have is to reload sys and call sys.setdefaultencoding('utf-8') or something.

UPDATE: Jinja2 2.8 contains some updates related to implicit string conversions. This gives me the idea that it is possible to go without sys.setdefaultencoding('utf-8') by overriding __add__ methods of the unicode type and make sure that it is type is used first while concatenating strings.

https://github.com/mitsuhiko/jinja2/issues/511



来源:https://stackoverflow.com/questions/28642781/hack-jinja2-to-encode-from-utf-8-instead-of-ascii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!