Forramidcode in pyramid和pyramid_simplefrom:设置固定的语言环境

时间:2011-10-14 09:59:34

标签: python pyramid formencode

我知道我可以在python shell中运行以下代码:

import formencode
ne = formencode.validators.NotEmpty()
formencode.api.set_stdtranslation(languages=["it"])
try:
    ne.to_python("")
except formencode.api.Invalid, e:
    print str(e)

并打印

  

Inserire un valore

现在如何使用pyramid_simpleform和Formencode在我的金字塔应用程序中获得相同的结果?

1 个答案:

答案 0 :(得分:4)

我刚刚找到了办法,但我不确定它是最好的...无论如何,我混合了Mako i18n recipesimpleform documentation以及Pylons如何做的信息它(pylons.decorators里面的PylonsFormEncodeState)我想出了以下内容......

我订阅了这样的NewRequest事件:

config.add_subscriber("myproject.subscribers.add_localizer",
                      "pyramid.events.NewRequest")

然后定义add_localizer

from pyramid import i18n
from formencode import api as formencode_api

def add_localizer(event):
    request = event.request
    localizer = i18n.get_localizer(request)
    if not hasattr(localizer, "old_translate"):
        localizer.old_translate = localizer.translate # Backup the default method
    request.localizer = localizer
    request.translate = lambda x: localizer.translate(i18n.TranslationString(x))

    # Set FormEncode language for this request
    formencode_api.set_stdtranslation(languages=["it"]) # This should depend on the user's selection or whatever

    def multiple_gettext(value):
        # Try default translation first
        t = localizer.old_translate(i18n.TranslationString(value))
        if t == value:
            # It looks like translation failed, let's try FormEncode
            t = formencode_api._stdtrans(value)
        return t

    localizer.translate = multiple_gettext