Exemplo n.º 1
0
    def get_connection(self):
        """Get a connection from the pool

        This method returns an PooledPyMySQLConnection instance which
        has a reference to the pool that created it, and the next available
        MySQL connection.

        When the MySQL connection is not connect, a reconnect is attempted.

        Raises PoolError on errors.

        Returns a PooledPyMySQLConnection instance.
        """
        with CONNECTION_POOL_LOCK:
            try:
                cnx = self._cnx_queue.get(block=False)
            except queue.Empty:
                raise PoolError("Failed getting connection; pool exhausted")

            if not is_connected(
                    cnx) or self._config_version != cnx._pool_config_version:
                cnx = Connection(**self._cnx_config)
                try:
                    cnx.ping(reconnect=True)
                except Exception as e:
                    # Failed to reconnect, give connection back to pool
                    self._queue_connection(cnx)
                    raise
                cnx._pool_config_version = self._config_version

            return PooledPyMySQLConnection(self, cnx)
Exemplo n.º 2
0
    def add_connection(self, cnx=None):
        """Add a connection to the pool

        This method instantiates a Connection using the configuration
        passed when initializing the PyMySQLConnectionPool instance or using
        the set_config() method.
        If cnx is a Connection instance, it will be added to the
        queue.

        Raises PoolError when no configuration is set, when no more
        connection can be added (maximum reached) or when the connection
        can not be instantiated.
        """
        with CONNECTION_POOL_LOCK:
            if not self._cnx_config:
                raise PoolError("Connection configuration not available")

            if self._cnx_queue.full():
                raise PoolError("Failed adding connection; queue is full")

            if not cnx:
                cnx = Connection(**self._cnx_config)
                cnx._pool_config_version = self._config_version
            else:
                if not isinstance(cnx, Connection):
                    raise PoolError(
                        "Connection instance not subclass of MySQLConnection.")

            self._queue_connection(cnx)