Example #1
0
    def test_no_request_context(self):
        b = babel.Babel()
        app = flask.Flask(__name__)
        b.init_app(app)

        with app.app_context():
            assert isinstance(get_translations(), NullTranslations)
Example #2
0
    def test_no_request_context(self):
        b = babel.Babel()
        app = flask.Flask(__name__)
        b.init_app(app)

        with app.app_context():
            assert isinstance(get_translations(), NullTranslations)
Example #3
0
def translations():
    """Return a js file that will handle translations so Flask interpolation can be isolated"""
    template = render_template("js/translations.js",
                               translations=get_translations()._catalog)
    return Response(response=template,
                    status=200,
                    mimetype="application/javascript")
Example #4
0
def create_app():
    b = babel.Babel()
    @b.localeselector
    def get_locale():
        lang = getattr(g, 'lang', 'ko')
        if lang:
            return lang
        return  request.accept_languages.best_match(['en', 'ko', 'en'])

    app = Flask(__name__)
    b.init_app(app)

    with app.app_context():
        assert isinstance(get_translations(), NullTranslations)
    
    '''
    https://github.com/python-babel/flask-babel/tree/master/tests
    '''

    app.json_encoder = JSONEncoder

    from app.api.sample import sample_bp
    app.register_blueprint(sample_bp, url_prefix='')
    from app.api import base_bp
    app.register_blueprint(base_bp, url_prefix='')
    from app.api.hr import hr_bp
    app.register_blueprint(hr_bp, url_prefix='/api')

    return app
Example #5
0
    def catalog_view(self):
        js = [
            """"use strict";

(function() {
    var babel = {};
    babel.catalog = """
        ]

        translations = get_translations()
        # Here used to be an isinstance check for NullTranslations, but the
        # translation object that is "merged" by flask-babel is seen as an
        # instance of NullTranslations.
        catalog = translations._catalog.copy()

        # copy()ing the catalog here because we're modifying the original copy.
        for key, value in catalog.copy().items():
            if isinstance(key, tuple):
                text, plural = key
                if text not in catalog:
                    catalog[text] = {}

                catalog[text][plural] = value
                del catalog[key]

        js.append(json.dumps(catalog, indent=4))

        js.append(";\n")
        js.append(JAVASCRIPT)

        metadata = translations.gettext("")
        if metadata:
            for m in metadata.splitlines():
                if m.lower().startswith("plural-forms:"):
                    js.append("    babel.plural = ")
                    js.append(c2js(m.lower().split("plural=")[1]))

        js.append("""

    window.babel = babel;
    window.gettext = babel.gettext;
    window.ngettext = babel.ngettext;
    window._ = babel.gettext;
})();
""")

        resp = Response("".join(js))
        resp.headers["Content-Type"] = "text/javascript"
        return resp
Example #6
0
def get_translations():
    # If there is no context:  return None
    ctx = _request_ctx_stack.top
    if not ctx:
        return None

    # If context exists and contains a cached value, return cached value
    if hasattr(ctx, 'flask_user_translations'):
        return ctx.flask_user_translations

    # If App has not initialized Flask-Babel: return None
    app_has_initalized_flask_babel = 'babel' in current_app.extensions
    if not app_has_initalized_flask_babel:  # pragma no cover
        ctx.flask_user_translations = None
        return ctx.flask_user_translations

    # Prepare search properties
    import os
    import gettext as python_gettext
    from flask_babel import get_locale, get_translations, support
    domain = 'flask_user'
    locales = [get_locale()]
    languages = [str(locale) for locale in locales]

    # See if translations exists in Application dir
    app_dir = os.path.join(current_app.root_path, 'translations')
    filename = python_gettext.find(domain, app_dir, languages)
    if filename:
        ctx.flask_user_translations = support.Translations.load(app_dir,
                                                                locales,
                                                                domain=domain)

    # See if translations exists in Flask-User dir
    else:
        flask_user_dir = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'translations')
        ctx.flask_user_translations = support.Translations.load(flask_user_dir,
                                                                locales,
                                                                domain=domain)

    return ctx.flask_user_translations.merge(get_translations())
Example #7
0
 def gettext_no_interpolate(string):
     t = flask_babel.get_translations()
     if t is None:
         return string
     return t.ugettext(string)
Example #8
0
def get_client_translations(domain='client'):
    translations = get_translations()
    return {
        key: val
        for key, val in translations._catalog.items() if key and val
    }
Example #9
0
def template_context():
    """Inject variables into the template context."""
    # pylint: disable=protected-access
    catalog = get_translations()._catalog
    return dict(ledger=g.ledger, translations=catalog)
Example #10
0
 def gettext_no_interpolate(string):
     t = flask_babel.get_translations()
     if t is None:
         return string
     return t.ugettext(string)
Example #11
0
def gettext(string, **variables):
    """ Translate specified string."""
    translations = get_translations()
    if translations:
        return translations.ugettext(string) % variables
    return string % variables
Example #12
0
def translations() -> Any:
    """Get translations catalog."""
    # pylint: disable=protected-access
    return get_translations()._catalog