【问题标题】:Flask Babel Translations pathFlask Babel 翻译路径
【发布时间】:2014-10-21 13:45:28
【问题描述】:

我有一个使用 Flask Babel 翻译模板的 web 应用程序。 这个 webapp 可以通过将数据库名称添加到其 url 来使用多个数据库,例如:

myapp.com/<dbname>

问题是翻译路径在 babel 中是硬编码的:

    def list_translations(self):
        """Returns a list of all the locales translations exist for.  The
        list returned will be filled with actual locale objects and not just
        strings.

        .. versionadded:: 0.6
        """
        dirname = os.path.join(self.app.root_path, 'translations')
        if not os.path.isdir(dirname):
            return []
        result = []
        for folder in os.listdir(dirname):
            locale_dir = os.path.join(dirname, folder, 'LC_MESSAGES')
            if not os.path.isdir(locale_dir):
                continue
            if filter(lambda x: x.endswith('.mo'), os.listdir(locale_dir)):
                result.append(Locale.parse(folder))
        if not result:
            result.append(Locale.parse(self._default_locale))
        return result

babel 强迫我进入名为“translations”的目录和名为“messages.mo”的语言文件

我尝试了整个互联网,但仍然没有明确的解决方案。

我想到了一个想法,是否可以用 babelex 更改 babel,然后我可以覆盖翻译路径?

【问题讨论】:

    标签: python flask internationalization python-babel flask-babel


    【解决方案1】:

    ... 几年后,得到一个线索 in github 。从 0.6 版开始,Babel 似乎没有记录不良的参数 BABEL_TRANSLATION_DIRECTORIES。那么 Flask 应用骨架应该是

    # example.py
    from flask import Flask
    app = Flask('example')
    
    # change path of messages.mo file
    app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'i18n'
    
    # add translation capacity
    from flask.ext.babel import Babel
    babel = Babel(app)
    
    # define routes and so on ...
    

    使用此配置,Flask 将首先在 dir 'i18n' 中查找翻译。

    一个非常基本的 jinja 模板

    {{_('hello')}}
    

    具有 2 种语言的目录树。文件messages.po应该包含'hello'的翻译

    /myProject
      /i18n
        /en
          /LC_MESSAGES
            messages.po
        /fr
          /LC_MESSAGES
            messages.po
      example.py
    

    奖励:多个目录使用

    app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'i18n;second_dir;third_dir'
    

    【讨论】:

      【解决方案2】:

      解决方案是安装 Flask Babelex 而不是 Babel。

      【讨论】:

        【解决方案3】:

        为什么不直接将flask babel源码加载到你的项目中并进行修改呢?

        【讨论】:

        • 问题是该应用程序已经安装在多个服务器上的许多实例中,我只能访问Webapp目录,而不是完整的应用程序。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多