# copied from elasticsearch-dsl/connections.py
from elasticsearch import Elasticsearch
[docs]class Connections(object):
"""
Class responsible for holding connections to different clusters. Used as a
singleton in this module.
"""
def __init__(self):
self._kwargs = {}
self._conns = {}
[docs] def add_connection(self, alias, conn):
"""
Add a connection object, it will be passed through as-is.
"""
self._conns[alias] = conn
[docs] def remove_connection(self, alias):
"""
Remove connection from the registry. Raises ``KeyError`` if connection
wasn't found.
"""
errors = 0
for d in (self._conns, self._kwargs):
try:
del d[alias]
except KeyError:
errors += 1
if errors == 2:
raise KeyError("There is no connection with alias %r." % alias)
[docs] def create_connection(self, alias="default", **kwargs):
"""
Construct an instance of ``elasticsearch.Elasticsearch`` and register
it under given alias.
"""
conn = self._conns[alias] = Elasticsearch(**kwargs)
return conn
[docs] def get_connection(self, alias="default"):
"""
Retrieve a connection, construct it if necessary (only configuration
was passed to us). If a non-string alias has been passed through we
assume it's already a client instance and will just return it as-is.
Raises ``KeyError`` if no client (or its definition) is registered
under the alias.
"""
# do not check isinstance(Elasticsearch) so that people can wrap their
# clients
if not isinstance(alias, str):
return alias
# connection already established
try:
return self._conns[alias]
except KeyError:
pass
# if not, try to create it
try:
return self.create_connection(alias, **self._kwargs[alias])
except KeyError:
# no connection and no kwargs to set one up
raise KeyError("There is no connection with alias %r." % alias)
connections = Connections()
configure = connections.configure
add_connection = connections.add_connection
remove_connection = connections.remove_connection
create_connection = connections.create_connection
get_connection = connections.get_connection