1

我已经在 Flask-babel 周围挖掘了一段时间,但似乎无法url routing通过简单的方式获得blueprint. 这是精简的应用程序

在我的__ init __.py 文件上,

app = Flask(__name__)
babel.init_app(app)


@babel.localeselector
def get_locale():
    return g.get('lang_code', 'fr')


from .mod_main import mod_main as main_blueprint
app.register_blueprint(main_blueprint,url_prefix='/<lang_code>')

蓝图views.py文件中

@mod_main.url_defaults
def add_language_code(endpoint, values):
    values.setdefault('lang_code', g.lang_code)


@mod_main.url_value_preprocessor
def pull_lang_code(endpoint, values):
    g.lang_code = values.pop('lang_code')


@mod_main.route('/', methods=['GET', 'POST'])
def index():
    return render_template('main/index.html')

只要我导航到http://localhost:5000/fr但当我导航到http://localhost:5000/(没有 lang)时,我得到 404 错误。正常 - 因为蓝图需要一个 lang_code 作为前缀。

当用户第一次导航到http://localhost:5000/(没有 lang)时,我希望该站点以“fr”的语言显示页面。如果用户然后将其切换到英语并导航到http://localhost:5000/,我希望它以英语而不是法语显示。似乎无法让这个工作!

4

1 回答 1

3

我终于找到了解决方案——我需要做的就是before_request在应用程序上添加一个函数来检查 request.view_args 并根据会话变量提供正确的语言。

我还发现g烧瓶中的变量仅对活动请求有效,不能用于跨请求存储值。(因为我试图跨请求将 lang 存储在 g 变量上 - 必须使用会话变量来跨请求传输值)

我刚刚在这里上传了一个精简的应用程序,实现了带有蓝图的 babel:https ://github.com/shankararul/simple-babel

于 2014-11-30T17:27:33.060 回答