Flask-babel: translation per user
See documentation: http://pythonhosted.org/Flask-Babel/#configuration:
from flask import g, request@babel.localeselectordef get_locale(): # if a user is logged in, use the locale from the user settings user = getattr(g, 'user', None) if user is not None: return user.locale # otherwise try to guess the language from the user accept # header the browser transmits. We support de/fr/en in this # example. The best match wins. return request.accept_languages.best_match(['de', 'fr', 'en'])
You can get locale from User in database, from url, domain or subdomain, from user request headers. You can have own locale detection method, but you need return locale with babel.localeselector
. If babel.localeselector
can't get locale, then it use default locale in BABEL_DEFAULT_LOCALE
.
When you get right locale, you also need create translates .po
and .mo
for each supported locale. Do not forget that each translated string must be marked as for translation.