【问题标题】:Django: How to detect if translation is activated?Django:如何检测翻译是否被激活?
【发布时间】:2009-10-22 08:18:24
【问题描述】:

django.utils.translation.get_language() 如果未激活翻译,则返回默认语言环境。有没有办法查明翻译是否被激活(通过translation.activate())?

【问题讨论】:

  • 在我看来不像,但我可能错了。

标签: python django internationalization


【解决方案1】:

非常老套,但至少应该在 1.1.1 中工作:

import django.utils.translation.trans_real as trans
from django.utils.thread_support import currentThread

def isactive():
  return currentThread() in trans._active

【讨论】:

  • Hacky 但并不可怕。 +1
【解决方案2】:

取决于应用程序和架构...

Ignacio 提供的Hack 应该可以工作,但是你将在未激活的线程中运行什么?

我会使用 Ignacio 解决方案 + 添加所有线程可见的队列、monkeypatch trans_real.activate 函数并在队列中设置属性。

【讨论】:

    【解决方案3】:

    始终检查源代码以解决此类问题,这比发布到网络上要快!

    Django 在幕后使用了黑魔法,并使用某种调度程序来模拟禁用的翻译。

    对你来说最好的方法是:

    import setttings
    assert settings.USE_i18N == True
    

    【讨论】:

    • 在发布答案之前,请务必确保您理解问题。我在问translation.activate() 是否已被调用。
    • 另外你不应该直接导入设置。首选方式是from django.conf import settings,有关更多信息,请参阅文档。请更正您的代码。
    猜你喜欢
    • 2013-02-24
    • 1970-01-01
    • 2018-10-10
    • 2018-05-14
    • 2015-07-27
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多