Toc
  1. 使用flask-babel 给flask应用多语言
    1. 安装
    2. 使用
      1. py文件里的内容
      2. 创建本地化翻译文件:
Toc
0 条结果
lllyyb
flask多语言
2019/09/26   282 字 flask python flask-babel

使用flask-babel 给flask应用多语言

Flask-Babel 是一个 Flask 的扩展,在 babel, pytz 和 speaklater 的帮助下添加 i18n 和 l10n 支持到任何 Flask 应用。它内置了一个时间格式化的支持,同样内置了一个非常简单和友好的 gettext 翻译的接口。

安装

pip install flask-babel

使用

py文件里的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from datetime import datetime
from flask_babel import Babel, refresh, gettext, format_datetime

# time = format_datetime(datetime.now()) # 翻译日期格式

app.config.update(
......
BABEL_DEFAULT_LOCALE='zh',
......
)

babel = Babel(app)


@babel.localeselector
def get_locale():
# if a user is logged in, use the locale from the user settings
locale = session.get('locale', None)
if locale is not None:
return locale
session['locale'] = request.accept_languages.best_match(['zh', 'en']) # 没有session的话会自动选择最合适的语言
return session['locale']


@babel.timezoneselector
def get_timezone():
timezone = session.get('timezone', None)
if timezone is not None:
return timezone

创建本地化翻译文件:

  • 首先创建一个Babel的配置文件,’babel.cfg’
  • 在babel.cfg文件中添加下面内容
    1
    2
    3
    [python: **.py]
    [jinja2: **/templates/**.html]
    extensions=jinja2.ext.autoescape,jinja2.ext.with_
  • 执行 pybabel extract -F babel.cfg -o messages.pot .
  • 执行 pybabel update -i messages.pot -d translations,在生成的message.po 文件中将对应的多语言翻译写上去。
  • 最后执行 pybabel compile -d translations
本文作者:lybtt
版权声明:本文首发于lybtt的博客,转载请注明出处!