Flask-Babel do not translate anything in a web project

Tags: , , , ,



Description of my usage:

This is my project structure(basically base on Flask Web Development):

├── README.md
├── app
│   ├── __init__.py
│   ├── admin
│   │   ├── __init__.py
│   │   ├── user_admin.py
│   ├── auth
│   │   ├── __init__.py
│   │   ├── forms.py
│   │   ├── views.py
│   ├── decorators.py
│   ├── main
│   │   ├── __init__.py
│   │   ├── errors.py
│   │   ├── forms.py
│   │   ├── views.py
│   ├── models.py
│   └── templates
│       ├── auth
│       │   ├── login.html
│       │   └── register.html
│       ├── base.html
│       ├── edit-profile.html
│       ├── index.html
│       ├── layout.html
│       └── user.html
├── babel.cfg
├── config.py
├── manage.py
├── migrations
│   ├── README
│   ├── alembic.ini
│   ├── env.py
│   ├── script.py.mako
│   └── versions
│       ├── 20c68396e6d8_.py
├── requirement.txt
├── test
└── translations
    └── zh_CN
        └── LC_MESSAGES
            ├── messages.mo
            └── messages.po

Configuration in /babel.cfg and /app/__init__.py

babel.cfg:

[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_

app/__init__.py:

# ...
from flask_babelex import Babel

babel = Babel()

@babel.localeselector
def get_locale():
    return 'zh_CN'

def create_app(config_name):
    #...
    babel.init_app(app)
    return app

Then I follow the Flask-Babel document

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

Run $ pybabel extract -F babel.cfg -k lazy_gettext -o messages.pot .

They do have found all the gettexts and lazy_gettexts.

Run $ pybabel init -i messages.pot -d translations -l zh_CN

This generate a /translations/zh_CN/LC_MESSAGES/messages.po for me. And I fixed some translations in it.(including delete the # .fuzzy)

Finally I run $ pybabel compile -d translations. This generate the /tranlations/zh_CN/LC_MESSAGES/messages.mo successfully.

But nothing has been translated……And I really don’t know how to fix this bug.

I was really screwed up with this for several days.

For more information,I put this project on Github.

Answer

because the actual locale name parsed by babel is “zh_Hans_CN”, name your translation directory to be “zh_Hans_CN”, and it will be found.



Source: stackoverflow