简体   繁体   English

Python/Django:ugettext_lazy 函数如何与运算符 % 完全配合?

[英]Python/Django: how does the ugettext_lazy function exactly work with operator %?

I am using python 2.7 and had issue with lines like: LOG.warning(_("text"))我正在使用 python 2.7 并且遇到类似以下行的问题: LOG.warning(_("text"))

This won't work as LOG.warning is expecting a string (str) and ugettext_lazy only knows how to render unicode.这不会起作用,因为 LOG.warning 需要一个字符串 (str),而 ugettext_lazy 只知道如何呈现 unicode。

Now the solution I found was to force unicode rendering before calling the logger:现在我找到的解决方案是在调用记录器之前强制进行 unicode 渲染:

    text = 'Test trans'
    LOG.warning(u"%s" % _(text))

However, I was surprised to noticed that this code also work:然而,我很惊讶地注意到这段代码也有效:

LOG.warning(_(Test trans %(test)s.') % {'test': 1})
LOG.warning(_('Test trans %s.') % 1)

Can somebody explain why?有人可以解释为什么吗? Does the % operator calls for unicode rendering before replacing the variable? %运算符是否在替换变量之前调用 unicode 渲染?

Thanks in advance.提前致谢。

The u prefix in ugettext_lazy means that the return value of this function is a Unicode string. ugettext_lazyu前缀表示这个函数的返回值是一个 Unicode 字符串。 The _lazy suffix means that the return value becomes lazy, that is, the return value only becomes a Unicode string at the absolutely last opportunity, when a string operation is done on it. _lazy后缀意味着返回值变得惰性,即返回值仅在绝对最后的机会,当对其进行字符串操作时才变为 Unicode 字符串。

Try running this under python2 manage.py shell to see what I mean:尝试在python2 manage.py shell下运行它以了解我的意思:

>>> from django.utils.translation import ugettext_lazy as _
>>> _("hi")
<django.utils.functional.__proxy__ object at 0x10fa23b10>
>>> _("hi") + ""
u'hi'
>>> _("hi %s") % "hello"
u'hi hello'

I'm assuming that your assumption that LOG.warning only accepts non-Unicode strings and lazy strings is correct.我假设您认为LOG.warning只接受非 Unicode 字符串和惰性字符串的假设是正确的。 In your case, maybe you have your logging configured to do nothing with warning log messages, and so the lazy strings that you are passing to LOG.warning are never evaluated and never converted to normal non-lazy Unicode strings.在您的情况下,您可能已将日志记录配置为对警告日志消息不执行任何操作,因此您传递给LOG.warning的惰性字符串永远不会被评估,也永远不会转换为正常的非惰性 Unicode 字符串。

Compare with ugettext and gettext_lazy , and you'll see what I mean.ugettextgettext_lazy进行比较,您就会明白我的意思。

By the way, I highly recommend upgrading to Python 3, the way it deals with Unicode is much clearer and easy to follow in general than Python 2.顺便说一句,我强烈建议升级到 Python 3,它处理 Unicode 的方式通常比 Python 2 更清晰易懂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM