Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Using Babel's LazyProxy with gettext

Posted by Dan Jacob on 2010-05-03 @ 16:14 and filed in Internationalization

Babel has a lazy proxy function under babel.support, that you can use when you need a lazy gettext string.

For example if you are defining field labels in a WTForms class:

from wtforms import Form, fields
from myapp.utils import ugettext_lazy as _

class MyForm(Form):
    name = fields.TextField(_("Name"))

The string will be translated in the request thread rather than immediately, as in most cases you will want to provide the translation based on user settings (browser, session or database).

from flask import g
from babel.support import LazyProxy

def ugettext(s):
    # we assume a before_request function
    # assigns the correct user-specific
    # translations
    return g.translations.ugettext(s)

ugettext_lazy = LazyProxy(ugettext)

This snippet by Dan Jacob can be used freely for anything you like. Consider it public domain.