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
def test_multiple_apps(): app1 = flask.Flask(__name__) b1 = babel.Babel(app1, default_locale='de_DE') app2 = flask.Flask(__name__) b2 = babel.Babel(app2, default_locale='de_DE') with app1.test_request_context() as ctx: assert babel.gettext('Yes') == 'Ja' assert ('de_DE', 'messages') in b1.domain_instance.get_translations_cache(ctx) with app2.test_request_context() as ctx: assert 'de_DE', 'messages' not in b2.domain_instance.get_translations_cache( ctx)
def test_multiple_directories(self): """ Ensure we can load translations from multiple directories. """ b = babel.Babel() app = flask.Flask(__name__) app.config.update({ 'BABEL_TRANSLATION_DIRECTORIES': ';'.join(( 'translations', 'renamed_translations' )), 'BABEL_DEFAULT_LOCALE': 'de_DE' }) b.init_app(app) with app.test_request_context(): translations = b.list_translations() assert(len(translations) == 2) assert(str(translations[0]) == 'de') assert(str(translations[1]) == 'de') assert gettext( u'Hello %(name)s!', name='Peter' ) == 'Hallo Peter!'
def init_app(self, app, *args, **kwargs): self.app = app app.wsgi_app = LanguageCodeFromPathMiddleware(app.wsgi_app, self) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['babel_by_url'] = self self.babel = app.extensions.get( 'babel', flask_babel.Babel(app, *args, **kwargs)) self.default_locale = self.babel.default_locale locales = set(self.babel.list_translations()) locales.add(self.default_locale) self.locale_map = dict([(l.language, l) for l in locales]) @self.babel.localeselector def get_locale(): return self.lookup_locale() @app.before_request def init_request_locale(): language_code = request.environ.get('LANGUAGE_CODE_FROM_URL') if language_code and language_code != self.get_language_code(): self.set_language_code(language_code) flask_babel.refresh() app.context_processor(self.context_processor)
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)
def test_force_locale_with_threading(): app = flask.Flask(__name__) b = babel.Babel(app) @b.localeselector def select_locale(): return 'de_DE' semaphore = Semaphore(value=0) def first_request(): with app.test_request_context(): with babel.force_locale('en_US'): assert str(babel.get_locale()) == 'en_US' semaphore.acquire() thread = Thread(target=first_request) thread.start() try: with app.test_request_context(): assert str(babel.get_locale()) == 'de_DE' finally: semaphore.release() thread.join()
def test_domain(): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') domain = babel.Domain(domain='test') with app.test_request_context(): assert domain.gettext('first') == 'erste' assert babel.gettext('first') == 'first'
def test_basics(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') with app.test_request_context(): assert gettext(u'Hello %(name)s!', name='Peter') == 'Hallo Peter!' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 3) == u'3 Äpfel' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 1) == u'1 Apfel'
def test_refreshing(self): app = flask.Flask(__name__) babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna' babel.refresh() assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM'
def test_lazy_gettext_defaultdomain(): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE', default_domain='test') first = lazy_gettext('first') with app.test_request_context(): assert str(first) == 'erste' app.config['BABEL_DEFAULT_LOCALE'] = 'en_US' with app.test_request_context(): assert str(first) == 'first'
def test_lazy_gettext(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') yes = lazy_gettext(u'Yes') with app.test_request_context(): assert text_type(yes) == 'Ja' app.config['BABEL_DEFAULT_LOCALE'] = 'en_US' with app.test_request_context(): assert text_type(yes) == 'Yes'
def init_extensions(self): mail_app = flask_mail.Mail(self.flask_app) babel = flask_babel.Babel(self.flask_app) babel.locale_selector_func = self.locale_selector self.extensions.update( babel=babel, mail=mail_app, )
def setup_flask_babel(app): import flask_babel babel = flask_babel.Babel(app) app.jinja_env.globals['format_datetime'] = flask_babel.format_datetime app.jinja_env.globals['format_date'] = flask_babel.format_date app.jinja_env.globals['format_currency'] = flask_babel.format_currency return babel
def test_lazy_ngettext(): app = flask.Flask(__name__) babel.Babel(app, default_locale='de_DE') one_apple = lazy_ngettext(u'%(num)s Apple', u'%(num)s Apples', 1) with app.test_request_context(): assert str(one_apple) == '1 Apfel' assert one_apple.__html__() == '1 Apfel' two_apples = lazy_ngettext(u'%(num)s Apple', u'%(num)s Apples', 2) with app.test_request_context(): assert str(two_apples) == u'2 Äpfel' assert two_apples.__html__() == u'2 Äpfel'
def test_custom_formats(self): app = flask.Flask(__name__) app.config.update(BABEL_DEFAULT_LOCALE='en_US', BABEL_DEFAULT_TIMEZONE='Pacific/Johnston') b = babel.Babel(app) b.date_formats['datetime'] = 'long' b.date_formats['datetime.long'] = 'MMMM d, yyyy h:mm:ss a' d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'April 12, 2010 3:46:00 AM'
def test_no_formatting(self): """ Ensure we don't format strings unless a variable is passed. """ app = flask.Flask(__name__) babel.Babel(app) with app.test_request_context(): assert gettext(u'Test %s') == u'Test %s' assert gettext(u'Test %(name)s', name=u'test') == u'Test test' assert gettext(u'Test %s') % 'test' == u'Test test'
def test_basics(self): app = flask.Flask(__name__) babel.Babel(app) n = 1099 with app.test_request_context(): assert babel.format_number(n) == u'1,099' assert babel.format_decimal(Decimal('1010.99')) == u'1,010.99' assert babel.format_currency(n, 'USD') == '$1,099.00' assert babel.format_percent(0.19) == '19%' assert babel.format_scientific(10000) == u'1E4'
def test_cache(mocker): load_mock = mocker.patch("babel.support.Translations.load", side_effect=babel.support.Translations.load) app = flask.Flask(__name__) b = babel.Babel(app, default_locale="de_DE") @b.localeselector def select_locale(): return the_locale # first request, should load en_US the_locale = "en_US" with app.test_request_context() as ctx: assert b.domain_instance.get_translations_cache(ctx) == {} assert babel.gettext("Yes") == "Yes" assert load_mock.call_count == 1 # second request, should use en_US from cache with app.test_request_context() as ctx: assert set(b.domain_instance.get_translations_cache(ctx)) == { ("en_US", "messages") } assert babel.gettext("Yes") == "Yes" assert load_mock.call_count == 1 # third request, should load de_DE from cache the_locale = "de_DE" with app.test_request_context() as ctx: assert set(b.domain_instance.get_translations_cache(ctx)) == { ("en_US", "messages") } assert babel.gettext("Yes") == "Ja" assert load_mock.call_count == 2 # now everything is cached, so no more loads should happen! the_locale = "en_US" with app.test_request_context() as ctx: assert set(b.domain_instance.get_translations_cache(ctx)) == { ("en_US", "messages"), ("de_DE", "messages"), } assert babel.gettext("Yes") == "Yes" assert load_mock.call_count == 2 the_locale = "de_DE" with app.test_request_context() as ctx: assert set(b.domain_instance.get_translations_cache(ctx)) == { ("en_US", "messages"), ("de_DE", "messages"), } assert babel.gettext("Yes") == "Ja" assert load_mock.call_count == 2
def test_force_locale(self): app = flask.Flask(__name__) b = babel.Babel(app) @b.localeselector def select_locale(): return 'de_DE' with app.test_request_context(): assert str(babel.get_locale()) == 'de_DE' with babel.force_locale('en_US'): assert str(babel.get_locale()) == 'en_US' assert str(babel.get_locale()) == 'de_DE'
def test_force_locale(): pytest.skip("This test needs to be run with --assert=reinterp or --assert=plain flag") app = Flask(__name__) b = babel.Babel(app) @b.localeselector def select_locale(): return 'de_DE' with app.test_request_context(): assert str(babel.get_locale()) == 'de_DE' with force_locale('en_US'): assert str(babel.get_locale()) == 'en_US' assert str(babel.get_locale()) == 'de_DE'
def __init__(self, p_config, p_package_name, p_app_control, p_master_connector, p_is_master): super(StatusServer, self).__init__( p_config=p_config, p_name="Web Server", p_package_name=p_package_name, p_use_login_manager=p_is_master, p_login_view=self.login_view, p_logged_out_endpoint=BLUEPRINT_NAME + '.' + INDEX_VIEW_NAME) self._blueprint = None self._is_master = p_is_master self._appcontrol = p_app_control self._master_connector = p_master_connector self._stat_dict = {} self._server_exception = None if self._is_master: self._blueprint = flask.Blueprint(BLUEPRINT_NAME, little_brother.__name__, static_folder="static") BLUEPRINT_ADAPTER.assign_view_handler_instance( p_blueprint=self._blueprint, p_view_handler_instance=self) BLUEPRINT_ADAPTER.check_view_methods() self._app.register_blueprint(blueprint=self._blueprint, url_prefix=self._config.base_url) self._api_view_handler = api_view_handler.ApiViewHandler( p_app=self._app, p_app_control=self._appcontrol, p_master_connector=self._master_connector) self._app.jinja_env.filters[ 'datetime_to_string'] = self.format_datetime self._app.jinja_env.filters['time_to_string'] = self.format_time self._app.jinja_env.filters['date_to_string'] = self.format_date self._app.jinja_env.filters[ 'simple_date_to_string'] = self.format_simple_date self._app.jinja_env.filters['seconds_to_string'] = self.format_seconds self._app.jinja_env.filters['boolean_to_string'] = self.format_boolean self._app.jinja_env.filters['format'] = self.format self._babel = flask_babel.Babel(self._app) self._babel.localeselector(self.get_request_locale) gettext.bindtextdomain("messages", "little_brother/translations")
def test_template_basics(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') t = lambda x: flask.render_template_string('{{ %s }}' % x) with app.test_request_context(): assert t("gettext('Hello %(name)s!', name='Peter')") == 'Hallo Peter!' assert t("ngettext('%(num)s Apple', '%(num)s Apples', 3)") == u'3 Äpfel' assert t("ngettext('%(num)s Apple', '%(num)s Apples', 1)") == u'1 Apfel' assert flask.render_template_string(''' {% trans %}Hello {{ name }}!{% endtrans %} ''', name='Peter').strip() == 'Hallo Peter!' assert flask.render_template_string(''' {% trans num=3 %}{{ num }} Apple {%- pluralize %}{{ num }} Apples{% endtrans %} ''', name='Peter').strip() == u'3 Äpfel'
def test_basics(self): app = flask.Flask(__name__) babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' assert babel.format_date(d) == 'Apr 12, 2010' assert babel.format_time(d) == '1:46:00 PM' with app.test_request_context(): app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna' assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM' assert babel.format_date(d) == 'Apr 12, 2010' assert babel.format_time(d) == '3:46:00 PM' with app.test_request_context(): app.config['BABEL_DEFAULT_LOCALE'] = 'de_DE' assert babel.format_datetime(d, 'long') == \ '12. April 2010 um 15:46:00 MESZ'
def configure_i18n(app): babel = flask_babel.Babel(app) @babel.localeselector def get_locale(): if not request: if hasattr(g, 'locale'): return g.locale raise RuntimeError( 'Babel is used outside of request context, please set g.locale' ) locales = app.config['LOCALES'].keys() locale = request.cookies.get('locale') if locale in locales: return locale return request.accept_languages.best_match(locales) @app.before_request def before_request(): g.locale = flask_babel.get_locale()
def setup_flask_babel(app): import flask_babel from flask import request from flask import session from flask_login import current_user from flasquelistan import models babel = flask_babel.Babel(app) app.jinja_env.globals['format_datetime'] = flask_babel.format_datetime app.jinja_env.globals['format_date'] = flask_babel.format_date app.jinja_env.globals['format_currency'] = flask_babel.format_currency app.jinja_env.globals['locale'] = flask_babel.get_locale @babel.localeselector def get_locale(): # Check if user is logged in, if so, use the users stored preferences if current_user.is_authenticated: if request.args.get('lang'): current_user.lang = request.args.get('lang') models.db.session.commit() flask_babel.refresh() return current_user.lang # Check the session cookie if the user isn't logged in else: if request.args.get('lang'): session['lang'] = request.args.get('lang') flask_babel.refresh() return session.get('lang', None) @babel.timezoneselector def get_timezone(): # Used to change the time zone. # user = getattr(g, 'user', None) # if user is not None: # return user.timezone return None return babel
def test_different_domain(self): """ Ensure we can load translations from multiple directories. """ b = babel.Babel() app = flask.Flask(__name__) app.config.update({ 'BABEL_TRANSLATION_DIRECTORIES': 'translations_different_domain', 'BABEL_DEFAULT_LOCALE': 'de_DE', 'BABEL_DOMAIN': 'myapp' }) b.init_app(app) with app.test_request_context(): translations = b.list_translations() assert(len(translations) == 1) assert(str(translations[0]) == 'de') assert gettext(u'Good bye') == 'Auf Wiedersehen'
def test_custom_locale_selector(self): app = flask.Flask(__name__) b = babel.Babel(app) d = datetime(2010, 4, 12, 13, 46) the_timezone = 'UTC' the_locale = 'en_US' @b.localeselector def select_locale(): return the_locale @b.timezoneselector def select_timezone(): return the_timezone with app.test_request_context(): assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM' the_locale = 'de_DE' the_timezone = 'Europe/Vienna' with app.test_request_context(): assert babel.format_datetime(d) == '12.04.2010 15:46:00'
# Login configuration login = flask_login.LoginManager() login.login_view = "ui.login" @login.unauthorized_handler def handle_needs_login(): return flask.redirect( flask.url_for('ui.login', next=flask.request.endpoint)) # Rate limiter limiter = limiter.LimitWraperFactory() # Application translation babel = flask_babel.Babel() @babel.localeselector def get_locale(): translations = list(map(str, babel.list_translations())) return flask.request.accept_languages.best_match(translations) # Proxy fixer class PrefixMiddleware(object): def __call__(self, environ, start_response): prefix = environ.get('HTTP_X_FORWARDED_PREFIX', '') if prefix: environ['SCRIPT_NAME'] = prefix return self.app(environ, start_response)
def create_app(): # Load Flask config app = flask.Flask(__name__) try: with open( os.path.realpath(os.path.join(os.path.dirname(__file__), "../config.json")) ) as f: conf = json.load(f) app.config.update(conf.get("flask", "")) except FileNotFoundError: pass app.config.setdefault( "data_dir", os.path.realpath(os.path.join(os.path.dirname(__file__), "../data")) ) # Put the short hash of the current git commit in the config rev = subprocess.run( ["git", "rev-parse", "--short", "HEAD"], universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) app.config["version"] = rev.stdout app.config["SWAGGER_UI_DOC_EXPANSION"] = "list" # Setup i18n extensions babel = flask_babel.Babel(app) app.jinja_env.add_extension("jinja2.ext.i18n") @babel.localeselector def get_locale(): translations = [locale.language for locale in babel.list_translations()] use_lang = flask.request.args.get("uselang") if use_lang in translations: return use_lang elif flask.request.cookies.get("lang") in translations: return flask.request.cookies["lang"] else: return flask.request.accept_languages.best_match(translations) @app.context_processor def locale_data(): """Used to always pass l10n data to template""" def setlang_url(lang): return flask.url_for( flask.request.endpoint, setlang=lang, **flask.request.view_args, **flask.request.args ) return dict( current_locale=flask_babel.get_locale(), available_locales=babel.list_translations(), setlang_url=setlang_url, ) from web import frontend, api import deploy app.register_blueprint(frontend.bp) app.register_blueprint(api.bp) app.register_blueprint(deploy.bp) return app, babel
# Debugging toolbar if app.config.get("DEBUG"): import flask_debugtoolbar toolbar = flask_debugtoolbar.DebugToolbarExtension(app) # Profiler if app.config.get("DEBUG"): app.wsgi_app = profiler.ProfilerMiddleware(app.wsgi_app, restrictions=[30]) # Manager commnad manager = flask_script.Manager(app) manager.add_command('db', flask_migrate.MigrateCommand) # Babel configuration babel = flask_babel.Babel(app) translations = list(map(str, babel.list_translations())) @babel.localeselector def get_locale(): return flask.request.accept_languages.best_match(translations) # Login configuration login_manager = flask_login.LoginManager() login_manager.init_app(app) login_manager.login_view = "ui.login" @login_manager.unauthorized_handler