A simple but robust connection pool (with multiplexing) base on PyMySQL, mainly used for multi threads mode, which also compatible with single thread mode.
GNU General Public License v3.0
179
stars
49
forks
source link
AttributeError: module 'pymysqlpool' has no attribute 'ConnectionPool' #27
Traceback (most recent call last):
File "/usr/src/app/./main.py", line 42, in
db_manager = DatabaseService(app.config)
File "/usr/src/app/./services/database_service.py", line 19, in init
self.pool = pymysqlpool.ConnectionPool(
on docker debian dist:
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 12 (bookworm)
Release: 12
Codename: bookworm
But in Windows 10 it works. There are the same version of python and same version of the packages.
import pymysql.cursors
import pymysqlpool
import time
from log.log import Log
Inicializando el logger
logger = Log.get_logger()
class DatabaseService:
def init(self, config):
"""
Constructor de la clase DatabaseManager. Inicializa la conexión
al pool de conexiones con la configuración proporcionada.
:param config: Diccionario con la configuración de la base de datos.
"""
self.pool = pymysqlpool.ConnectionPool(
host=config['MYSQL_HOST'],
user=config['MYSQL_USER'],
password=config['MYSQL_PASSWORD'],
db=config['MYSQL_DB'],
cursorclass=pymysql.cursors.DictCursor,
autocommit=True,
size=5,
maxsize=7,
pre_create_num=2,
name='pool1'
)
self.connection = None
def __enter__(self):
"""
Método especial para permitir el uso de DatabaseManager
dentro de un bloque with.
:return: Una conexión a la base de datos.
"""
self.connection = self.get_connection_with_retry()
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
"""
Método especial que se llama cuando se sale del bloque with,
asegurando que la conexión se cierre.
:param exc_type: Tipo de excepción.
:param exc_val: Valor de la excepción.
:param exc_tb: Traceback de la excepción.
"""
self.close()
def get_connection_with_retry(self, max_retries=5, delay=1):
"""
Intenta obtener una conexión del pool, reintentando hasta
max_retries veces con un retraso de delay segundos entre intentos.
:param max_retries: Número máximo de reintentos.
:param delay: Retraso entre reintentos en segundos.
:return: Una conexión a la base de datos.
"""
retry_count = 0
while retry_count < max_retries:
try:
return self.pool.get_connection()
except pymysqlpool.GetConnectionFromPoolError:
retry_count += 1
time.sleep(delay)
logger.error(f"Can't get connection after {max_retries} retries")
raise pymysqlpool.GetConnectionFromPoolError(f"Can't get connection after {max_retries} retries")
def close(self):
"""
Cierra la conexión actual a la base de datos si existe.
"""
if self.connection is None:
logger.warning("No connection to close.")
else:
try:
self.connection.close()
self.connection = None
logger.info("Connection closed successfully.")
except Exception as e:
logger.error(f"Error closing connection: {e}")
I got this error:
Traceback (most recent call last): File "/usr/src/app/./main.py", line 42, in
db_manager = DatabaseService(app.config)
File "/usr/src/app/./services/database_service.py", line 19, in init
self.pool = pymysqlpool.ConnectionPool(
on docker debian dist:
No LSB modules are available. Distributor ID: Debian Description: Debian GNU/Linux 12 (bookworm) Release: 12 Codename: bookworm
But in Windows 10 it works. There are the same version of python and same version of the packages.
import pymysql.cursors import pymysqlpool import time from log.log import Log
Inicializando el logger
logger = Log.get_logger()
class DatabaseService: def init(self, config): """ Constructor de la clase DatabaseManager. Inicializa la conexión al pool de conexiones con la configuración proporcionada.