flask的support多國語言的方式,與python本身的gettext
方式相同,都是去parse檔案裡頭含有gettext
這類的語法,然後在將檔案轉成.po
檔,去編輯相關的對應文字,接著放在相對應的folder,例如zh
和en
的字眼,最後在轉成.mo
,實際執行gettext
會讀取.mo
。
Demo screenshot
假設預設的配置如下:
1 | . |
mysettings.cfg
設定預設的語系(在多國語系找不到時,將會預設英文):1
BABEL_DEFAULT_LOCALE="en"
透過from_pyfile
載入:1
app.config.from_pyfile('mysettings.cfg')
預設web接受的語系:1
2
3
4
5
6
7
8
9
10@babel.localeselector
def get_locale():
# if a user is logged in, use the locale from the user settings
user = getattr(g, 'user', None)
if user is not None:
return user.locale
# otherwise try to guess the language from the user accept
# header the browser transmits. We support de/fr/en in this
# example. The best match wins.
return request.accept_languages.best_match(['en','zh'])
產生.po和.mo檔
babel.cfg
設定要parse的路徑:1
2
3[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
接著只要在專案的根目錄執行以下command,就會取得messages.pot檔案:
1 | pybabel extract -F babel.cfg -o messages.pot . |
編輯好message.mo,初始化語系路徑以及設定語系:
1 | pybabel init -i messages.pot -d translations -l zh |
產生translations/de/LC_MESSAGES/messages.po
此路徑。
最後在將translations
底下的.po
檔案轉換成.mo
檔即可:1
pybabel compile -d translations