def _get_pooled_connection(**kwargs): """Return a pooled MySQL connection""" # If no pool name specified, generate one try: pool_name = kwargs['pool_name'] except KeyError: pool_name = generate_pool_name(**kwargs) # Setup the pool, ensuring only 1 thread can update at a time with CONNECTION_POOL_LOCK: if pool_name not in _CONNECTION_POOLS: _CONNECTION_POOLS[pool_name] = MySQLConnectionPool(**kwargs) elif isinstance(_CONNECTION_POOLS[pool_name], MySQLConnectionPool): # pool_size must be the same check_size = _CONNECTION_POOLS[pool_name].pool_size if ('pool_size' in kwargs and kwargs['pool_size'] != check_size): raise PoolError("Size can not be changed " "for active pools.") # Return pooled connection try: return _CONNECTION_POOLS[pool_name].get_connection() except AttributeError: raise InterfaceError( "Failed getting connection from pool '{0}'".format(pool_name))
def test_generate_pool_name(self): self.assertRaises(errors.PoolError, pooling.generate_pool_name) config = {'host': 'ham', 'database': 'spam'} self.assertEqual('ham_spam', pooling.generate_pool_name(**config)) config = {'database': 'spam', 'port': 3377, 'host': 'example.com'} self.assertEqual('example.com_3377_spam', pooling.generate_pool_name(**config)) config = { 'user': '******', 'database': 'spam', 'port': 3377, 'host': 'example.com'} self.assertEqual('example.com_3377_ham_spam', pooling.generate_pool_name(**config))
def connect(*args, **kwargs): """Create or get a MySQL connection object In its simpliest form, Connect() will open a connection to a MySQL server and return a MySQLConnection object. When any connection pooling arguments are given, for example pool_name or pool_size, a pool is created or a previously one is used to return a PooledMySQLConnection. Returns MySQLConnection or PooledMySQLConnection. """ if 'fabric' in kwargs: return mysql.connector.fabric.connect(*args, **kwargs) # Pooled connections if any([key in kwargs for key in CNX_POOL_ARGS]): # If no pool name specified, generate one try: pool_name = kwargs['pool_name'] except KeyError: pool_name = generate_pool_name(**kwargs) # Setup the pool, ensuring only 1 thread can update at a time with CONNECTION_POOL_LOCK: if pool_name not in _CONNECTION_POOLS: _CONNECTION_POOLS[pool_name] = MySQLConnectionPool( *args, **kwargs) elif isinstance(_CONNECTION_POOLS[pool_name], MySQLConnectionPool): # pool_size must be the same check_size = _CONNECTION_POOLS[pool_name].pool_size if ('pool_size' in kwargs and kwargs['pool_size'] != check_size): raise PoolError("Size can not be changed " "for active pools.") # Return pooled connection try: return _CONNECTION_POOLS[pool_name].get_connection() except AttributeError: raise InterfaceError( "Failed getting connection from pool '{0}'".format(pool_name)) # Regular connection return MySQLConnection(*args, **kwargs)
def test__get_pooled_connection(self): dbconfig = tests.get_mysql_config() mysql.connector._CONNECTION_POOLS.update({'spam': 'ham'}) self.assertRaises(errors.InterfaceError, mysql.connector.connect, pool_name='spam') mysql.connector._CONNECTION_POOLS = {} mysql.connector.connect(pool_name='ham', **dbconfig) self.assertTrue('ham' in mysql.connector._CONNECTION_POOLS) cnxpool = mysql.connector._CONNECTION_POOLS['ham'] self.assertTrue(isinstance(cnxpool, pooling.MySQLConnectionPool)) self.assertEqual('ham', cnxpool.pool_name) mysql.connector.connect(pool_size=5, **dbconfig) pool_name = pooling.generate_pool_name(**dbconfig) self.assertTrue(pool_name in mysql.connector._CONNECTION_POOLS)
def __init__(self, pool_size=5, pool_name=None, pool_reset_session=True, **kwargs): """Initialize Initialize a MySQL connection pool with a maximum number of connections set to pool_size. The rest of the keywords arguments, kwargs, are configuration arguments for MySQLConnection instances. """ self._pool_size = None self._pool_name = None self._reset_session = pool_reset_session self._set_pool_size(pool_size) self._set_pool_name(pool_name or generate_pool_name(**kwargs)) self._cnx_config = {} self._cnx_queue = queue.Queue(self._pool_size) self._config_version = uuid4() if kwargs: self.set_config(**kwargs) cnt = 0 while cnt < self._pool_size: self.add_connection() cnt += 1
def __init__(self, user, password, host, port, database, pool_size=0): """ 建立连接池 :param user :param password: :param host: :param port: :param database: :param pool_size: 如果为0,直接建立普通短连接;如果大于0,则建立长连接的连接池 """ self._database = database self._host = host self._user = user self._port = port self._password = password self._pool_size = pool_size if pool_size < 0: raise ValueError('pool_size must >= 0') elif pool_size > 0: pool_name = pooling.generate_pool_name(user=user, host=host, port=port, database=database) if pool_name not in MYSQL_POOL: MYSQL_POOL[pool_name] = pooling.MySQLConnectionPool( pool_name=pool_name, pool_size=pool_size, user=user, password=password, host=host, port=port, database=database, autocommit=False) self.pool = MYSQL_POOL[pool_name]