Formencode in pyramid and pyramid_simplefrom: set fixed locale

757 views Asked by At

I know I can run the following code in 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)

and get printed

Inserire un valore

Now how do I get the same result im my pyramid app using pyramid_simpleform with Formencode?

1

There are 1 answers

1
Joril On

I've just found a way to do it, but I'm not sure it's the best one... Anyway, I mixed information from the Mako i18n recipe, the simpleform documentation and how Pylons did it (the PylonsFormEncodeState inside pylons.decorators) and I came up with the following...

I subscribe to a NewRequest event like this:

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

and then define 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