【问题标题】:Flask App not calling Babel localeselectorFlask App 不调用 Babel localeselector
【发布时间】:2019-01-12 21:25:37
【问题描述】:

我正在使用 Flask-Babel 为我的 Flask 应用程序添加本地化,​​但我似乎无法更改语言。我按照所有 Babel 说明创建 po/mo 文件 - 我不相信我的问题与翻译数据有关......我不知道如何更改语言......这似乎会/应该很明显。

我的调试显示babel.localeselector 没有被调用。我的实现调用refresh(),我认为应该调用babel.localeselector(不知何故......因为我不知道它是如何工作的,因为refresh() 命令似乎只是从应用程序上下文中删除了一些键......我不知道这如何触发对babel.localeselector 的调用)

app = Flask(__name__)
babel = Babel(app)

@babel.localeselector
def get_locale():
    # if a user is logged in, use the locale from the user settings
    user = User.get_by_id(session['user_id'])
    if user is not None: return user.lang
    return 'en'

并且,当用户登录时,会调用此函数,

from flask_babel import refresh

def login(user_id):
    # Gets called when user successfully logs in
    refresh()

我已确认正在呼叫refresh()。 但语言没有改变。

更新: 这个也试过了,

from flask import current_app
from common.models import User
from flask_babel import refresh

def login(user_id):
    # Gets called when user successfully logs in
    user = User.get_by_id(user_id)
    current_app.config['BABEL_DEFAULT_LOCALE'] = user.lang
    refresh()

【问题讨论】:

    标签: python flask gettext python-babel flask-babel


    【解决方案1】:

    找出问题所在。我正在使用,

    import gettext
    _ = gettext.gettext
    

    而不是,

    from flask_babel import gettext as _
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多