Flask + Flask-Security + Babel not working

浪子不回头ぞ 提交于 2020-01-05 05:29:47

问题


I have setup with Flask + Babel + Flask Security. Created all translation like this:

  • root
    • main.py
    • translations
      • ru
        • LC_MESSAGES
          • messages.mo
          • messages.po

In main.py there is part to setup language which executes:

@babel.localeselector
def get_locale():
    user = getattr(g, 'user', None)
    if user is not None:
        print("User locale {}".format(user.locale))
        return user.locale
    # I put here constant to test
    return 'ru'

But http://localhost/login stayed untranslated. Can you please advice where else to dig? No errors in logs even with Debug = True


回答1:


I have found that Flask-Security doesn't work with Babel out of box! This Pull Request fixes it partially from WTF processing perspective. To be able to translate Jinja2 templates as well following need to be amended in core.py

def render_template(self, *args, **kwargs):
    # Provide i18n support even if flask-babel is not installed
    # or enabled.
    kwargs['gettext'] = gettext
    kwargs['ngettext'] = ngettext
    kwargs['_'] = _
    return render_template(*args, **kwargs)



回答2:


FWIW, with me simply changing my imports to

from flask_babelex import Babel, gettext, lazy_gettext

made it all work fine with Flask-Security.




回答3:


You should tell to your app that your use a particular locale. I did that as follows:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore
from .models import User, Role, 
from flask_babel import Babel

app = Flask(__name__)
db = SQLAlchemy(app)

user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

babel = Babel(app, 'ru')


来源:https://stackoverflow.com/questions/42375487/flask-flask-security-babel-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!