Spaces:
Sleeping
Sleeping
from library.librerias import sqlite3, Queue, threading | |
DB_PATH = "database/anhelados.db" | |
class DatabaseConnection: | |
""" | |
Clase para gestionar las conexiones a la base de datos con un pool. | |
""" | |
_instance = None | |
_lock = threading.Lock() | |
_connection_pool = Queue(maxsize=5) | |
def __new__(cls): | |
""" | |
Crea una nueva instancia de la clase si no existe. | |
""" | |
with cls._lock: | |
if cls._instance is None: | |
cls._instance = super().__new__(cls) | |
cls._instance.conn = cls._instance._create_connection() | |
return cls._instance | |
def _create_connection(self): | |
""" | |
Crea una conexi贸n a la base de datos. | |
""" | |
if not self._connection_pool.empty(): | |
return self._connection_pool.get() | |
else: | |
connection = sqlite3.connect(DB_PATH) | |
connection.row_factory = sqlite3.Row | |
return connection | |
def get_connection(self): | |
""" | |
Obtener el objeto de conexi贸n de la base de datos. | |
""" | |
return self._instance._create_connection() | |
def release_connection(self): | |
""" | |
Liberar la conexi贸n de nuevo al pool. | |
""" | |
if self._instance is not None: | |
self._connection_pool.put(self._instance.conn) | |
self._instance.conn = None # Marcar la instancia como sin conexi贸n | |