Hack Jinja2编码从`utf-8`而不是`ascii`? [英] Hack Jinja2 to encode from `utf-8` instead of `ascii`?

查看:145
本文介绍了Hack Jinja2编码从`utf-8`而不是`ascii`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jinja2在处理之前将所有模板变量转换为unicode。任何人都可以找到发生这种情况的地方?

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

问题是它假定字符串是 ascii ,但是我们(在综合)在内部使用 utf-8 ,我们的ORM(HyperDB)将对象属性恢复到 utf-8 在传递给模板之前,在每个视图中自动将它们全部转换为 unicode

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.

推荐答案

Armin的答案:


不幸的是,这是不可能的。 Jinja使用Python提供的速度的2.x上的默认字符串强制。没有保证的电话来做某事unicode。你唯一的选择是重新加载sys并调用sys.setdefaultencoding('utf-8')或某些东西。

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.

更新: Jinja2 2.8包含一些与隐式字符串转换相关的更新。这给我的想法是,可以通过覆盖 __添加__ sys.setdefaultencoding('utf-8') > unicode类型的方法,并确保它是类型首先在连接字符串时使用。

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

这篇关于Hack Jinja2编码从`utf-8`而不是`ascii`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆