Change language Flask Babel manually

依然范特西╮ 提交于 2019-11-30 20:12:01

问题


I'm using Flask Babel to translate my Flask Python app. At moment I only have the translation mechanism by locale but what if the user besides his location wants to change the location to english? Is there any way to change the locale manually?

This is my Flask Babel function that gets the user locale and returns the language. It is on my __init__.py file.

@babel.localeselector
def get_locale():
    print "LANGUAGE PT"
    #return 'de' -> manually change to the desired language
    request.accept_languages.best_match(LANGUAGES.keys()) 

I really appreciate any help!

Best regards


回答1:


A good way to do this is shown in the docs of Flask-Admin

@babel.localeselector
def get_locale():
    if request.args.get('lang'):
        session['lang'] = request.args.get('lang')
    return session.get('lang', 'en')

Now, you could try a French version of the application at: http://localhost:5000/admin/?lang=fr.

You can still specify the default language via BABEL_DEFAULT_LOCALE.



来源:https://stackoverflow.com/questions/41686778/change-language-flask-babel-manually

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!