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

  1.  Surround all strings in html templates like below
    {{_('String')}}
  2. Run next command to map all strings 

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

  3. 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 :

  1.  Enter translation of msgid strings to msgstr objects. Escape single quota (\') in translated text!
  2. 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:

  1. pybabel extract -F babel.cfg -o messages.pot .
  2. Check messages.pot for appearing word "fuzzy", delete related string.
  3. pybabel update -i messages.pot -d translations
  4. Check *.po files for "fuz" strings, delete them, check the tail of the file - sometimes translations can be commented and placed there.
  5. pybabel compile -d translations