Python flask_babel.Babel() Examples

The following are 6 code examples of flask_babel.Babel(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_babel , or try the search function .
Example #1
Source File: engine.py    From appkernel with Apache License 2.0 6 votes vote down vote up
def __init_babel(self):
        self.babel = Babel(self.app)
        # translations = Translations.load('translations')
        # translations.merge(Translations.load())
        # todo: support for multiple plugins
        supported_languages = []
        for supported_lang in self.cfg_engine.get('appkernel.i18n.languages', ['en-US']):
            supported_languages.append(supported_lang)
            if '-' in supported_lang:
                supported_languages.append(supported_lang.split('-')[0])

        def get_current_locale():
            with self.app.app_context():
                best_match = request.accept_languages.best_match(supported_languages, default='en')
                return best_match.replace('-', '_')

        self.babel.localeselector(get_current_locale)
        # catalogs = gettext.find('locale', 'locale', all=True)
        # self.logger.info('Using message catalogs: {}'.format(catalogs)) 
Example #2
Source File: app_object.py    From docassemble with MIT License 6 votes vote down vote up
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    from docassemble.base.config import daconfig
    import docassemble.webapp.database
    import docassemble.webapp.db_object
    connect_string = docassemble.webapp.database.connection_string()
    alchemy_connect_string = docassemble.webapp.database.alchemy_connection_string()
    app.config['SQLALCHEMY_DATABASE_URI'] = alchemy_connect_string
    app.secret_key = daconfig.get('secretkey', '38ihfiFehfoU34mcq_4clirglw3g4o87')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = docassemble.webapp.db_object.init_flask()
    db.init_app(app)
    csrf = CSRFProtect()
    csrf.init_app(app)
    babel = Babel()
    babel.init_app(app)
    if daconfig.get('behind https load balancer', False):
        if proxyfix_version >= 15:
            app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
        else:
            app.wsgi_app = ProxyFix(app.wsgi_app)
    if 'cross site domains' in daconfig:
        CORS(app, origins=daconfig['cross site domains'], supports_credentials=True)
    return app, csrf, babel 
Example #3
Source File: flask_app.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, import_name: str) -> None:
        shared_web_path = os.path.abspath(os.path.dirname(__file__))
        static_folder = os.path.join(shared_web_path, 'static')
        super().__init__(import_name, static_folder=static_folder)
        super().register_error_handler(DoesNotExistException, self.not_found)
        super().register_error_handler(exceptions.NotFound, self.not_found)
        super().register_error_handler(exceptions.InternalServerError, self.internal_server_error)
        super().route('/unauthorized/')(self.unauthorized)
        super().route('/logout/')(self.logout)
        super().route('/authenticate/')(self.authenticate)
        super().route('/authenticate/callback/')(self.authenticate_callback)
        super().route('/api/gitpull', methods=['POST'])(api.process_github_webhook)
        super().route('/api/commit')(api.commit_id)
        super().route('/robots.txt')(self.robots_txt)
        super().route('/favicon<rest>')(self.favicon)
        self.url_build_error_handlers.append(self.external_url_handler)
        if self.config.get('SERVER_NAME') is None:
            self.config['SERVER_NAME'] = configuration.get_optional_str('flask_server_name')
        self.config['menu'] = []
        self.config['js_url'] = ''
        self.config['css_url'] = ''
        self.config['commit-id'] = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode()
        self.config['branch'] = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip().decode()
        self.config['SESSION_COOKIE_DOMAIN'] = configuration.get_optional_str('flask_cookie_domain')

        translations = os.path.abspath(os.path.join(shared_web_path, 'translations'))
        self.config['BABEL_TRANSLATION_DIRECTORIES'] = translations
        self.babel = Babel(self)
        localization.init(self.babel)
        self.api_root = Blueprint('api', import_name, url_prefix='/api/')
        self.api = Api(self.api_root, title=f'{import_name} API')
        self.register_blueprint(self.api_root) 
Example #4
Source File: localization.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def init(babel: Babel) -> None:
    LANGUAGES.extend([str(locale) for locale in babel.list_translations()])
    babel.localeselector(get_locale) 
Example #5
Source File: app.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def configure_coverage(app):
    """Setup coverage related extensions."""
    # setup chanjo report
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True if app.debug else False
    if chanjo_api:
        chanjo_api.init_app(app)
        configure_template_filters(app)
        # register chanjo report blueprint
        app.register_blueprint(report_bp, url_prefix="/reports")

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        """Determine locale to use for translations."""
        accept_languages = current_app.config.get("ACCEPT_LANGUAGES", ["en"])

        # first check request args
        session_language = request.args.get("lang")
        if session_language in accept_languages:
            current_app.logger.info("using session language: %s", session_language)
            return session_language

        # language can be forced in config
        user_language = current_app.config.get("REPORT_LANGUAGE")
        if user_language:
            return user_language

        # try to guess the language from the user accept header that
        # the browser transmits.  We support de/fr/en in this example.
        # The best match wins.
        return request.accept_languages.best_match(accept_languages) 
Example #6
Source File: init.py    From GeoHealthCheck with MIT License 5 votes vote down vote up
def init():
        # Do init once
        app = Flask(__name__)

        # Read and override configs
        app.config.from_pyfile('config_main.py')
        app.config.from_pyfile('../instance/config_site.py')
        app.config.from_envvar('GHC_SETTINGS', silent=True)

        # Global Logging config
        logging.basicConfig(level=int(app.config['GHC_LOG_LEVEL']),
                            format=app.config['GHC_LOG_FORMAT'])

        app.config['GHC_SITE_URL'] = \
            app.config['GHC_SITE_URL'].rstrip('/')

        app.secret_key = app.config['SECRET_KEY']

        App.db_instance = SQLAlchemy(app)
        App.babel_instance = Babel(app)

        # Plugins (via Docker ENV) must be list, but may have been
        # specified as comma-separated string, or older set notation
        app.config['GHC_PLUGINS'] = to_list(app.config['GHC_PLUGINS'])
        app.config['GHC_USER_PLUGINS'] = \
            to_list(app.config['GHC_USER_PLUGINS'])

        # Concatenate core- and user-Plugins
        App.plugins_instance = \
            app.config['GHC_PLUGINS'] + app.config['GHC_USER_PLUGINS']

        # Needed to find Plugins
        home_dir = os.path.dirname(os.path.abspath(__file__))
        App.home_dir = sys.path.append('%s/..' % home_dir)

        # Finally assign app-instance
        App.app_instance = app
        App.count += 1
        LOGGER.info("created GHC App instance #%d" % App.count)