Class中的字符串未翻译

时间:2019-01-21 18:48:51

标签: python flask flask-babel

一个类中的字符串没有被翻译,下面的代码快照说明了这个问题。

应该发生的是,当您击中烧瓶路径时,两个消息均为英文。然后点击浏览器刷新,这两种消息都应该被翻译。只会翻译msg2。

味精和味精2的区别在于味精来自该类。

我可以从打印语句中得知,更改语言后,将调用localeselector,并且由于msg2已翻译,因此可以正确设置语言环境。它几乎像msg一样被缓存为英语,并且当显示在类中时,翻译器不会对其进行解析。

也许这是预期的限制? 如果是这种情况,首选的解决方法是什么?

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, session
from flask_babel import Babel
from flask_babel import refresh
from flask_babel import gettext as _

app = Flask(__name__)
app.secret_key = "qwerty"
app.config.update(SESSION_COOKIE_NAME='mymain')
app.config['BABEL_TRANSLATION_DIRECTORIES'] = "locale"
app.config["BABEL_DEFAULT_LOCALE"] = 'en'

babel = Babel(app)


class MyClass(object):

    def __init__(self):
        self.msg = _("Now is the time")

    def text(self):
        return self.msg


myclass = MyClass()
language = "en"


@app.route('/')
def index():
    global language

    print("language - index: {}".format(language))
    msg = myclass.text()
    msg2 = _("for all good men")

    # change language
    language = 'zh_Hans'
    app.config['BABEL_DEFAULT_LOCALE'] = 'zh_Hans'
    session['language'] = 'zh_Hans'
    refresh()

    # PROBLEM: On 2nd page refresh, msg2 is translated, msg is NOT
    return 'Index Page: {} {}'.format(msg, msg2)


@babel.localeselector
def get_locale():
    print("language localeselector: {}".format(language))
    return language


class BaseConfig(object):
    SUPPORTED_LANGUAGES = ['en', 'zh_Hans']
    BABEL_DEFAULT_LOCALE = 'en'
    BABEL_DEFAULT_TIMEZONE = 'UTC'


app.config.from_object(BaseConfig)
app.run(host="0.0.0.0", port=6800, debug=False)

和po文件,该文件被编译为mo文件。

# Chinese (Simplified) translations for PROJECT.
# Copyright (C) 2019 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2019.
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2019-01-21 13:39-0500\n"
"PO-Revision-Date: 2019-01-21 13:39-0500\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: zh_Hans\n"
"Language-Team: zh_Hans <LL@li.org>\n"
"Plural-Forms: nplurals=1; plural=0\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.6.0\n"

#: main.py:20
msgid "Now is the time"
msgstr "只是测试"

#: main.py:36
msgid "for all good men"
msgstr "只是测试"

0 个答案:

没有答案