Skip to content

Core

ConnHandler(connection_properties, max_retries=3, retry_wait_time=1, skip_connect=False, **kwargs)

Base abstract class for connection handlers. This class should not be instantiated directly.

This class should be used to handle connecting and doing queries/requests to servers. The _connect() method should be defined in subclasses as it will differ for each type of connection (SQL vs HTTP for example), or even for different types of servers (for example, in case of SQL: PostgreSQL, MySQL, MS SQL Server, etc.).

This already connects to the server unless skip_connect is set to True.

Parameters:

  • connection_properties

    (ConnProperties) –

    Object containing connection parameters.

  • max_retries

    (int, default: 3 ) –

    Number of retries that will be attempted when reconnecting or doing queries, by default 3

  • retry_wait_time

    (float, default: 1 ) –

    Wait time in seconds between each connection or query retry, by default 1

  • skip_connect

    (bool, default: False ) –

    If True, the connection will not be established when the object is created.

    If this is set toTrue, the user will need to manually call the reconnect() method when they want to connect to the server.

    By default False

  • **kwargs

    (dict, default: {} ) –

    Just kept here for compatibility.

Source code in echo_connhandler/core.py
@validate_call
def __init__(
    self,
    connection_properties: ConnProperties,
    max_retries: int = 3,
    retry_wait_time: float = 1,
    skip_connect: bool = False,
    **kwargs,  # pylint: disable=unused-argument # noqa
) -> None:
    """Method that initializes the handler.

    This already connects to the server unless skip_connect is set to True.

    Parameters
    ----------
    connection_properties : ConnProperties
        Object containing connection parameters.
    max_retries : int, optional
        Number of retries that will be attempted when reconnecting or doing queries, by default 3
    retry_wait_time : float, optional
        Wait time in seconds between each connection or query retry, by default 1
    skip_connect : bool, optional
        If True, the connection will not be established when the object is created.

        If this is set toTrue, the user will need to manually call the reconnect() method when they want to connect to the server.

        By default False
    **kwargs : dict, optional
        Just kept here for compatibility.

    """
    # checking if the connection properties are of the correct type
    if not isinstance(connection_properties, self._connprops_class):
        raise TypeError(
            f"connection_properties should be of type {self._connprops_class.__name__}, not {type(connection_properties).__name__}",
        )

    self.connection = None
    self.max_retries: int = max_retries
    self.retry_wait_time: float = retry_wait_time
    self.connection_properties: ConnProperties = connection_properties
    if not skip_connect:
        self.reconnect()

close()

Method that closes the connection.

Source code in echo_connhandler/core.py
def close(self) -> None:
    """Method that closes the connection."""
    if self.connection is not None:
        # try to close the connection
        try:
            self._close()
        except Exception:  # noqa
            pass
        finally:
            # try to delete the connection
            try:
                del self.connection
            except Exception:  # noqa
                pass
            finally:
                # set connection to None
                self.connection = None

reconnect()

Method to reconnect to the server.

Returns:

  • Self

    ConnHandler instance now connected to the server.

Source code in echo_connhandler/core.py
def reconnect(self) -> Self:
    """Method to reconnect to the server.

    Returns
    -------
    Self
        ConnHandler instance now connected to the server.
    """
    try:
        self.close()
    except Exception:  # noqa
        pass
    finally:
        self.connection = None

    connection_success = False
    attempt = 0
    first_error = None
    while not connection_success:
        try:
            self.connection = self._connect()
            connection_success = True
        except Exception as e:
            if attempt == 0:
                # storing the first error to be raised later
                first_error = e
            logger.exception(f"Attempt {attempt}: Could not connect to server using {self.connection_properties}")
            attempt += 1
            if attempt <= self.max_retries:
                sleep(self.retry_wait_time)
            else:
                raise RuntimeError(
                    f"Reachead {attempt} attempts and could not connect to server using {self.connection_properties}",
                ) from first_error

    return self

ConnProperties

Class that holds the properties used to establish a connection to a server (SQL, HTTP, etc.).

This should be created as a dataclass holding the relevant properties for each connection. This is an abstract class so it should not be instantiated directly.