Flask-Babel 转换 Flask-WTF SelectField

Flask-Babel convert Flask-WTF SelectField

我想用 Flask-Babel.

转换 Flask-WTF SelectField 值

这是我的代码片段:

from flask_babel import _, lazy_gettext as _l

class PaymentStatus(enum.Enum):
    REJECTED = 'REJECTED'
    COMPLETED = 'COMPLETED'
    EXPIRED = 'EXPIRED'

    def __str__(self):
        return self.value

payment_status = [(str(y), y) for y in (PaymentStatus)]

def course_list():
    return Course.query.all()

class PaymentForm(FlaskForm):
    course_name = QuerySelectField(_l('Course name'), validators=[required()], query_factory=course_list)
    status_of_payment = SelectField(_l('Payment Status'), choices=payment_status)
    # ...
    # ...

在那里,我想用 Flask-Babel.

本地化 SelectField choices 值和 QuerySelectField query_factory

是否可能..?如果可以,任何示例或参考教程将不胜感激:)

SelectField choices 可以由 lazy_gettext() 处理。

Quote from The Flask Mega-Tutorial Part XIII: I18n and L10n

Some string literals are assigned outside of a request, usually when the application is starting up, so at the time these texts are evaluated there is no way to know what language to use.

Flask-Babel provides a lazy evaluation version of _() that is called lazy_gettext().

from flask_babel import lazy_gettext as _l

class LoginForm(FlaskForm):
    username = StringField(_l('Username'), validators=[DataRequired()])
    # ...

对于choices

from flask_babel import _, lazy_gettext as _l

class PaymentStatus(enum.Enum):
    REJECTED = _l('REJECTED')
    COMPLETED = _l('COMPLETED')
    EXPIRED = _l('EXPIRED')

    def __str__(self):
        return self.value

QuerySelectField query_factory 接受从数据库 查询的值。 Flask-Babel/babel 不应处理这些值。导致数据库将数据存储在 Python 源代码之外。

可能的解决方案:

顺便说一句,The Flask Mega-Tutorial 由 Miguel Grinberg 制作,是一个非常有名的 Flask 教程。这些情况都包含在里面了。