Flask Babel quick reference
Setting up environment
Install Flask-Babel
pip install Flask-Babel
Add next lines to main application file
from flask import Flask from flask.ext.babel import Babel app = Flask(__name__) babel = Babel(app)app.config['BABEL_DEFAULT_LOCALE'] = 'ru'
Implement get_locale and get_timezone functions. get_locale function is responsible for displayed language.
@babel.localeselector def get_locale(): return 'ru'from flask import g, request@babel.timezoneselector def get_timezone(): user = getattr(g, 'user', None) if user is not None: return user.timezone
Add file babel.cfg with next contents
[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
Create translation
- Surround all strings in html templates like below
{{_('String')}} - Run next command to map all strings
pybabel extract -F babel.cfg -o messages.pot .
- Create translation template for finnish language
pybabel init -i messages.pot -d translations -l fi
Translation will appear at translations/fi/LC_MESSAGES/messages.po as a set ofr next entries:
#: templates/404.html:7
msgid "Страница не существует."
msgstr ""
#: templates/about_museum.html:9
msgid "ОПИСАНИЕ"
msgstr ""
Steps to enter new translation :
- Enter translation of msgid strings to msgstr objects. Escape single quota (\') in translated text!
Compile translations( or recompile in case of translation changes or fixies )
pybabel compile -d translations
If strings or their position in html templates where changed, the sequence is next:
- pybabel extract -F babel.cfg -o messages.pot .
- Check messages.pot for appearing word "fuzzy", delete related string.
- pybabel update -i messages.pot -d translations
- Check *.po files for "fuz" strings, delete them, check the tail of the file - sometimes translations can be commented and placed there.
- pybabel compile -d translations