diff --git a/application/libs/flask_elasticsearch/elasticsearch.py b/application/libs/flask_elasticsearch/elasticsearch.py index 56874fbb26487a274c0853b6dae769eccac884ae..9eee7d0272d6d023fa9290ae70b5d04f14b3ec5a 100644 --- a/application/libs/flask_elasticsearch/elasticsearch.py +++ b/application/libs/flask_elasticsearch/elasticsearch.py @@ -73,29 +73,42 @@ class FlaskElasticsearch: return getattr(ctx.elasticsearch, item) @staticmethod - def _get_config(): - """Retrieves Elasticsearch configuration from the current Flask application context.""" + def get_es_config() -> dict: + """Get Elasticsearch configuration from the current Flask application context.""" with current_app.app_context(): if current_app: config_helper = ConfigHelper(current_app) - cfg = config_helper.Elasticsearch - host = cfg.Host or 'localhost' - port = int(cfg.Port) or 9200 - user = cfg.User or None - password = cfg.Password or None - use_ssl = cfg.UseSsl == 'True' or False - verify_certs = cfg.VerifyCerts == 'False' - ca_certs = cfg.CaCerts or None - - options = dict( - hosts=[{'host': host, 'port': port}], - http_auth=None if not user else (user, password), - use_ssl=use_ssl, - verify_certs=verify_certs, - ca_certs=ca_certs - ) - - return options + return config_helper.Elasticsearch else: logger.error('Attempted to access application configuration outside of application context.') raise RuntimeError('Attempted to access application configuration outside of application context.') + + @staticmethod + def build_es_options(cfg) -> dict: + """ + Build Elasticsearch connection options from the configuration. + + :param cfg: Elasticsearch's configuration from the Flask application context. + """ + host = cfg.get('Host', 'localhost') + port = int(cfg.get('Port', 9200)) + user = cfg.get('User') + password = cfg.get('Password') + use_ssl = cfg.get('UseSsl', 'False') == 'True' + verify_certs = cfg.get('VerifyCerts', 'False') == 'True' + ca_certs = cfg.get('CaCerts') + + options = { + 'hosts': [{'host': host, 'port': port}], + 'http_auth': (user, password) if user and password else None, + 'use_ssl': use_ssl, + 'verify_certs': verify_certs, + 'ca_certs': ca_certs + } + + return options + + def _get_config(self) -> dict: + """Combines getting Elasticsearch configuration and building options.""" + cfg = self.get_es_config() + return self.build_es_options(cfg)