1. 安装Flask-babel
pip install flask-babel
2. 配置Flask-babel
from flask import Flask
from flask.ext.babel import Babel
app = Flask(__name__)
app.config.from_pyfile('babel.cfg')
babel = Babel(app)
3. 编辑babel.cfg文件,添加如下内容
[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
4. 配置默认语言
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():
s = _("Saturday")
return render_template('index.html', day=day)
if __name__ == '__main__':
app.debug = True
app.run()
5. 修改模板内容
<p>{{ _("Hello, world!") }}</p>
<p>{{ _("It's %(day)s today", day=day) }}</p>
6. 生成翻译模板
pybabel extract -F babel.cfg -o messages.pot .
7. 翻译模板
pybabel init -i messages.pot -d translations -l zh
8. 修改模板。
# Chinese translations for PROJECT.
# Copyright (C) 2015 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# Ray <csharp2002@hotmail>, 2015.
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: csharp2002@hotmail.com\n"
"POT-Creation-Date: 2015-03-29 22:46+0800\n"
"PO-Revision-Date: 2015-03-29 21:49+0800\n"
"Last-Translator: Ray <csharp2002@hotmail.com>\n"
"Language-Team: zh <LL@li.org>\n"
"Plural-Forms: nplurals=2; plural=(n != 1)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 1.3\n"
#: views.py:103
#,fuzzy, python-format
msgid "Articles tagged with:%(value)s"
msgstr "标记%(value)s主题的文章"
注:如果需要翻译的词语特别多,可以使用 poedit 软件管理。
9. 编译模板
pybabel compile -d translations
10. 区域切换。修改user模型,添加字段。
from flask import g, request
@babel.localeselector
def get_locale():
# 如果在g对象内有登入的用户对象则从用户对象中读取 locale 区域信息
user = getattr(g, 'user', None)
if user is not None:
return user.locale
# 此方法只需要返会一个区域字符串
return request.accept_languages.best_match(['de', 'fr', 'en'])
@babel.timezoneselector
def get_timezone():
"""此函数与 get_locale 类似,只是向babel提供获取时区的设置"""
user = getattr(g, 'user', None)
if user is not None:
return user.timezone
PS: 开启Flask-Babel后会设置jinja有缓存,临床表现为修改了template下面的html文件不能立即刷新显示在页面上了,这时候不要着急,设置如下代码即可。
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
如果再次修改了源文件,只需要执行以下三条命令即可。
> pybabel extract -F babel.cfg -o messages.pot .
> pybabel update -i messages.pot -d translations
> pybabel compile -d translations