Flask-Babel example

flask的support多國語言的方式,與python本身的gettext方式相同,都是去parse檔案裡頭含有gettext這類的語法,然後在將檔案轉成.po檔,去編輯相關的對應文字,接著放在相對應的folder,例如zhen的字眼,最後在轉成.mo,實際執行gettext會讀取.mo

Demo screenshot

Demo image

假設預設的配置如下:

1
2
3
4
5
6
7
.
├── app.py
├── babel.cfg
├── mysettings.cfg
├── README.md
└─── templates
   └── index.html

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

完成範例