class ConnectionPooled(object): '''数据库连接池类 创建连接池: pooled = ConnectionPooled(host='192.0.0.1', database='foo', pool_options=dict(max_size=5)) 获取一个未使用连接池的连接,并执行 SQL: pooled.execute(sql) pooled.connection.execute(sql) 使用连接池执行 SQL: with pooled.pool() as connection: connection.execute(sql) ''' # 这个连接,是不进入连接池的 _connection = None _defaults = dict(max_size=POOL_SIZE, max_usage=POOL_USAGES, ttl=POOL_TTL, idle=POOL_IDLE) def __init__(self, pool_options=None, **kwargs): self._configurations = kwargs pool_options = pool_options or {} self._pool = ConnectionPool(self._connect, **{ **self._defaults, **pool_options }) def _connect(self): return Connection(**self._configurations) @property def connection(self): if not self._connection: self._connection = self._connect() return self._connection def pool(self): return self._pool.item() def __getattr__(self, method): return getattr(self.connection, method)
from connection_pool import ConnectionPool class Connection(object): def __init__(self, **kwargs): self.args = kwargs self.state = 'Connected' def close(self): self.state = 'Closed' def connect(): return Connection() def close(connection): connection.close() pool = ConnectionPool(create=connect, close=close, max_size=10, max_usage=10000, idle=60, ttl=120) with pool.item() as connection: assert connection.state == 'Connected'