Flask-Babel 使用簡介(翻譯文檔)


最近用flask-bable翻譯一個項目,在網站上查找到有一個示例文檔,地址:http://translations.readthedocs.io/en/latest/flask-babel.html#

不過有些地方顯示的不對,特寫此文章進行更改,同時以備自己后期查看使用

安裝 Flask-Babel

Flask-Babel 是 Flask 的翻譯擴展工具。安裝命令如下:

pip install flask-babel

安裝它的時候會順便安裝 Babelpytzspeaklater 這三個包,其中 Babel 是 Python 的一個國際化工具包。pytz 是處理時區的工具包,speaklater 相當於是 Babel 的一個輔助工具,

我們這里集中在翻譯流程上,這幾個工具就供以后進一步了解吧。

Hello, World

接下來我們做一個簡單的 Hello World 程序,新建一個叫 hello 的文件夾,在其中創建一個叫 hello.py 的文件,內容如下:

注意:需要先安裝flask: pip install flask

#hello.py

from flask import Flask, render_template

 

app = Flask(__name__)

 

@app.route('/')

def hello():

    day = "Saturday"

    return render_template('index.html', day=day)

 

if __name__ == '__main__':

    app.run(debug=True)

然后在 hello.py 的同一級目錄下創建一個叫 templates 的文件夾,在其中寫一個 index.html,內容如下:

<p>Hello, world!</p>

<p>It's {{ day }} today.</p>

很簡單的 Hello World 程序,接下來我們要做的是讓這個站變成中文站。

更新程序和模板

再接下來就是翻譯了。翻譯需要用到 flask-babel 這個 flask 擴展。首先我們將這個 app “國際化”,為模板和 .py 文件中的每一個字符串添加一個 gettext 函數,由於 gettext 函數被引用的次數太多了,為了方便手寫,就將其 import 為 “_”:

from flask import Flask, render_template

 

from flaskext.babel import Babel, gettext as _

 

app = Flask(__name__)

app.config['BABEL_DEFAULT_LOCALE'] = 'zh'

babel = Babel(app)

 

@app.route('/')

def hello():

    day = _("Saturday")

    return render_template('index.html', day=day)

 

if __name__ == '__main__':

    app.run(debug=True)

然后修改模板:

<p>{{ _("Hello, world!") }}</p>

<p>{{ _("It's %(day)s today", day=day) }}</p>

你可以注意到我們對 app 的 locale 做了配置,然后用 babel 擴展將 app 再次初始化,並且將 .py 和 .html 中的字符串做了配置,讓它們都使用 gettext 這個函數。其中值得注意的是 gettext 的格式化字符串的參數。

如果直接用類似 "It's %s today" % day 是不行的。

這么一來,app 的語言其實是被寫死成中文了。其實你可以在 flask 程序中讓用戶選擇自己喜好的語言,或者依據瀏覽器設置用戶優先顯示的語言,詳細做法可以參考官方文檔中提到 localeselector 的部分。

設置 Babel

接下來我們要做的是 babel 的配置。在 hello.py 的同級目錄創建一個叫 babel.cfg 的文件,內容如下:

[python: **.py]

[jinja2: **/templates/**.html]

extensions=jinja2.ext.autoescape,jinja2.ext.with_

生成翻譯模板

這樣 babel 就知道要從哪些位置搜索要翻譯的字符串了。然后我們用 pybabel 生成要翻譯的 PO 模板文件,這個命令是 babel 這個工具包帶來的,生成翻譯模板命令如下:

$ pybabel extract -F babel.cfg -o messages.pot .

注意結尾的點“.”,這個點表示當前目錄,目錄是 pybabel 必須的參數,所以命令是無法執行成功的。messages.pot 就是我們生成的翻譯模板文件,內容大致如下:

# Translations template for PROJECT.

# Copyright (C) 2011 ORGANIZATION

# This file is distributed under the same license as the PROJECT project.

# FIRST AUTHOR , 2011.

#

#, fuzzy

msgid ""

msgstr ""

"Project-Id-Version: PROJECT VERSION\n"

"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"

"POT-Creation-Date: 2011-07-26 15:39+0800\n"

"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"

"Last-Translator: FULL NAME \n"

"Language-Team: LANGUAGE \n"

"MIME-Version: 1.0\n"

"Content-Type: text/plain; charset=utf-8\n"

"Content-Transfer-Encoding: 8bit\n"

"Generated-By: Babel 0.9.6\n"</code>

 

#: hello.py:11

msgid "Saturday"

msgstr ""

 

#: templates/index.html:1

msgid "Hello, world!"

msgstr ""

 

#: templates/index.html:2

#, python-format

msgid "It's %(day)s today"

msgstr ""

你可以修改里邊頭文件的信息,把個人和項目相關的資料加進去。

翻譯

接下來我們創建中文翻譯:

$ pybabel init -i messages.pot -d translations -l zh

這句命令會在 hello 文件夾中生成一個 translations 文件夾,要確保 flask 能找到翻譯內容,translations文件夾要和 templates 文件夾在同一個目錄中。接下來我們就可以進行翻譯了,修改 translations/zh/LC_MESSAGES/messages.po 文件,將其中的內容翻譯過來:

# Chinese (China) translations for PROJECT.

# Copyright (C) 2011 ORGANIZATION

# This file is distributed under the same license as the PROJECT project.

# FIRST AUTHOR , 2011.

#

msgid ""

msgstr ""

"Project-Id-Version: PROJECT VERSION\n"

"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"

"POT-Creation-Date: 2011-07-26 15:39+0800\n"

"PO-Revision-Date: 2011-07-26 09:07+0800\n"

"Last-Translator: FULL NAME \n"

"Language-Team: zh_CN \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 0.9.6\n"</code>

 

#: hello.py:11

msgid "Saturday"

msgstr "星期六"

 

#: templates/index.html:1

msgid "Hello, world!"

msgstr "哈羅,世界!"

 

#: templates/index.html:2

#, fuzzy, python-format

msgid "It's %(day)s today"

msgstr "今天是%(day)s"

PO文件的翻譯其實可以用專門的工具來編輯,比如 Poedit,不過小文件直接手譯就可以了。

編譯翻譯結果

翻譯完后執行下面的命令,為其編譯出 message.mo 文件:

$ pybabel compile -d translations

如果上述命令無法生成 messages.mo 文件,那你需要將 message.po 中的 #, fuzzy 刪除。

然后就算基本完成了。這時執行 python hello.py 就會看到翻譯的中文頁面了。

更新翻譯

有時我們需要對程序和模板做修改,翻譯也要隨之更新。更新后需要用前面的命令重新生成 messages.pot 文件,然后使用下面的命令將更新的內容 merge 到原來的翻譯中:

$ pybabel update -i messages.pot -d translations

最后再到對應 locale 的文件夾下更新翻譯並 compile 即可。

整個目錄結構圖下所示:

 代碼匯總:

1、新建babel.cfg:
[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
2、生成編譯模板
pybabel extract -F babel.cfg -o messages.pot .
3、翻譯
pybabel init -i messages.pot -d translations -l zh_Hans-CN
4、手動輸入中文
messages.mo
5、編譯翻譯結果
pybabel compile -d translations
6、更新翻譯
pybabel update -i messages.pot -d translations


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM