本文整理汇总了Python中psycopg2.pool.ThreadedConnectionPool类的典型用法代码示例。如果您正苦于以下问题:Python ThreadedConnectionPool类的具体用法?Python ThreadedConnectionPool怎么用?Python ThreadedConnectionPool使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ThreadedConnectionPool类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_decorator
def test_decorator(self):
"""
test using the decorator to access the pool
"""
global _connection_pool
min_connections = 1
max_connections = 5
test_number = 42
_connection_pool = ThreadedConnectionPool(min_connections,
max_connections,
**_database_credentials)
test_greenlet = DecoratorWriteGreenlet(test_number, 3.0)
rollback_greenlet = DecoratorRollbackGreenlet(3.0)
test_greenlet.start()
rollback_greenlet.start()
test_greenlet.join()
self.assertTrue(test_greenlet.successful())
rollback_greenlet.join()
self.assertTrue(rollback_greenlet.successful())
result = test_greenlet.value
self.assertEqual(result, [(test_number, )])
_connection_pool.closeall()
开发者ID:HackLinux,项目名称:nimbus.io,代码行数:29,代码来源:test_greenlet_connection_pool.py
示例2: test_context_manager
def test_context_manager(self):
"""
test using the context manager to access the pool
"""
min_connections = 1
max_connections = 5
test_number = 42
connection_pool = ThreadedConnectionPool(min_connections,
max_connections,
**_database_credentials)
test_greenlet = ContextWriteGreenlet(connection_pool, test_number, 3.0)
rollback_greenlet = ContextRollbackGreenlet(connection_pool, 3.0)
test_greenlet.start()
rollback_greenlet.start()
test_greenlet.join()
self.assertTrue(test_greenlet.successful())
rollback_greenlet.join()
self.assertTrue(rollback_greenlet.successful())
result = test_greenlet.value
self.assertEqual(result, [(test_number, )])
connection_pool.closeall()
开发者ID:HackLinux,项目名称:nimbus.io,代码行数:28,代码来源:test_greenlet_connection_pool.py
示例3: putconn
def putconn(self, conn):
"""
Returns connection back to pool.
"""
#calledBy = traceback.extract_stack()[-2]
#logging.info("PUTCONN - FILE: " + calledBy[0] + ", LINE: " + str(calledBy[1]) + ", METHOD: " + calledBy[2])
ThreadedConnectionPool.putconn(self, conn)
开发者ID:jzitnik,项目名称:z-pim,代码行数:10,代码来源:postgres.py
示例4: create_pool
def create_pool(self, conn_dict, limits):
"""
Create a connection pool
:param conn_dict: connection params dictionary
:type conn_dict: dict
"""
if conn_dict["Host"] is None:
self.host = 'localhost'
else:
self.host = conn_dict["Host"]
if conn_dict["Port"] is None:
self.port = '5432'
else:
self.port = conn_dict["Port"]
self.database = conn_dict["Database"]
self.user = conn_dict["User"]
self.passwd = conn_dict["Password"]
conn_params = "host='{host}' dbname='{db}' user='{user}' password='{passwd}' port='{port}'".format(
host=self.host, db=self.database, user=self.user, passwd=self.passwd, port=self.port
)
try:
logger.debug('creating pool')
self.pool = ThreadedConnectionPool(int(limits["Min"]), int(limits["Max"]), conn_params)
except Exception as e:
logger.exception(e.message)
开发者ID:a-wakeel,项目名称:pg-plain,代码行数:29,代码来源:pg_pool.py
示例5: _connect
def _connect(self):
global _CONNECTION_POOL
if _CONNECTION_POOL is None:
_CONNECTION_POOL = ThreadedConnectionPool(
config.DB_MIN_CONNECTIONS, config.DB_MAX_CONNECTIONS,
**config.DB_PARAMS)
if self._connection is not None:
raise RuntimeError("Connection still exists.")
self._connection = _CONNECTION_POOL.getconn()
self._connection.set_session(autocommit=True)
开发者ID:GreenelyAB,项目名称:TranslationsServer,代码行数:10,代码来源:postgres_db.py
示例6: __init__
class Database:
def __init__(self, connect_param):
self.__connect_param = connect_param
self.__pool = ThreadedConnectionPool(0, 10, self.__connect_param)
# get cursor and test it
# cur = self.cursor()
# cur.execute('SHOW transaction_read_only')
# standby = cur.fetchone()
# cur.close()
def get_connection(self):
return self.__pool.getconn()
def put_connection(self, connection):
self.__pool.putconn(connection)
开发者ID:stefanoberdoerfer,项目名称:jacobshack,代码行数:15,代码来源:_dbutil.py
示例7: Database
class Database():
def __init__(self, config):
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)
self._pool = ThreadedConnectionPool(1, 10,
database=config['DB_DATABASE'],
user=config['DB_USER'],
password=config['DB_PASSWORD'],
host=config['DB_HOST'],
async=False)
def get_connection(self):
return self._pool.getconn()
def put_away_connection(self, con):
self._pool.putconn(con)
开发者ID:imclab,项目名称:lys-reader,代码行数:16,代码来源:database.py
示例8: __init__
def __init__(self, host, port, database, username, password, session_ttl=24*60*60*365, anon_session_ttl=24*60*60, session_renew=0, anon_session_renew=0, min_connections=1, max_connections=10):
self.db = ThreadedConnectionPool(min_connections, max_connections, database=database, user=username, password=password, host=host, port=port)
self.create_tables()
self.session_ttl = session_ttl
self.anon_session_ttl = anon_session_ttl or self.session_ttl
self.session_renew = session_renew or self.session_ttl
self.anon_session_renew = anon_session_renew or self.anon_session_ttl
开发者ID:Coffee-fan,项目名称:Toto,代码行数:7,代码来源:postgresconnection.py
示例9: getconn
def getconn(self):
"""
Gets connection from parent class, enables AUTOCOMMIT and returns requested connection.
@rtype: object
@return: connection with isolation level set to autocommit
"""
#calledBy = traceback.extract_stack()[-2]
#logging.info("GETCONN - FILE: " + calledBy[0] + ", LINE: " + str(calledBy[1]) + ", METHOD: " + calledBy[2])
conn = ThreadedConnectionPool.getconn(self)
try:
#conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
conn.cursor().execute("SELECT 1")
except (psycopg2.OperationalError, psycopg2.InterfaceError, psycopg2.InternalError):
key = self._rused[id(conn)]
del self._rused[id(conn)]
conn = psycopg2.connect(self.dsn)
self._rused[id(conn)] = key
if Config.hstoreEnabled == True:
try:
psycopg2.extras.register_hstore(conn)
except Exception, e:
Config.hstoreEnabled = False
开发者ID:jzitnik,项目名称:z-pim,代码行数:27,代码来源:postgres.py
示例10: __init__
class DB:
def __init__(self, *args, **kwargs):
self.pool_params = (args, kwargs)
self.pool = None
self.campaigns = Campaigns(self)
self.worksets = Worksets(self)
self.tasks = Tasks(self)
self.labels = Labels(self)
self.logger = logging.getLogger(__name__)
def _initialize_pool(self):
if self.pool is None:
logger.info("Initializing connection pool.")
args, kwargs = self.pool_params
self.pool = ThreadedConnectionPool(
*args, cursor_factory=RealDictCursor, **kwargs)
def execute(self, sql):
with self.transaction() as transactor:
cursor = transactor.cursor()
cursor.execute(sql)
return cursor
@contextmanager
def transaction(self):
"""Provides a transactional scope around a series of operations."""
self._initialize_pool()
conn = self.pool.getconn()
try:
yield conn
conn.commit()
except:
conn.rollback()
raise
finally:
self.pool.putconn(conn)
@classmethod
def from_config(cls, config):
# Copy config as kwargs
params = {k: v for k, v in config['database'].items()}
params['minconn'] = params.get('minconn', 1)
params['maxconn'] = params.get('maxconn', 5)
return cls(**params)
开发者ID:amire80,项目名称:wikilabels,代码行数:46,代码来源:db.py
示例11: connect
def connect(self):
if self._connpool is not None:
return self
logger.info('connect to "%s"', self.name)
minconn = config.getint('database', 'minconn', default=1)
maxconn = config.getint('database', 'maxconn', default=64)
self._connpool = ThreadedConnectionPool(
minconn, maxconn, self.dsn(self.name))
return self
开发者ID:coopengo,项目名称:trytond,代码行数:9,代码来源:database.py
示例12: __init__
def __init__(self, config):
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)
self._pool = ThreadedConnectionPool(1, 10,
database=config['DB_DATABASE'],
user=config['DB_USER'],
password=config['DB_PASSWORD'],
host=config['DB_HOST'],
async=False)
开发者ID:imclab,项目名称:lys-reader,代码行数:9,代码来源:database.py
示例13: connect
def connect(self):
if self._connpool is not None:
return self
logger = logging.getLogger('database')
logger.info('connect to "%s"' % self.database_name)
host = CONFIG['db_host'] and "host=%s" % CONFIG['db_host'] or ''
port = CONFIG['db_port'] and "port=%s" % CONFIG['db_port'] or ''
name = "dbname=%s" % self.database_name
user = CONFIG['db_user'] and "user=%s" % CONFIG['db_user'] or ''
password = (CONFIG['db_password']
and "password=%s" % CONFIG['db_password'] or '')
minconn = int(CONFIG['db_minconn']) or 1
maxconn = int(CONFIG['db_maxconn']) or 64
dsn = '%s %s %s %s %s' % (host, port, name, user, password)
if dbgis:
self._connpool = GisThreadedConnectionPool(minconn, maxconn, dsn)
else:
self._connpool = ThreadedConnectionPool(minconn, maxconn, dsn)
return self
开发者ID:silpol,项目名称:tryton-bef,代码行数:19,代码来源:database.py
示例14: __init__
def __init__(self, settings):
from psycopg2.pool import ThreadedConnectionPool
dbsettings = settings['database']
self.pool = ThreadedConnectionPool(
minconn=1,
maxconn=settings['database']['conn_pool_size'],
database=dbsettings['name'],
user=dbsettings['username'],
password=dbsettings['password'],
host=dbsettings['host'],
port=dbsettings.get('port')
)
开发者ID:Zer0-,项目名称:common_components,代码行数:12,代码来源:db.py
示例15: __init__
class PgConnectionPool:
def __init__(self, *args, min_conns=1, keep_conns=10, max_conns=10,
**kwargs):
self._pool = ThreadedConnectionPool(
min_conns, max_conns, *args, **kwargs)
self._keep_conns = keep_conns
def acquire(self):
pool = self._pool
conn = pool.getconn()
pool.minconn = min(self._keep_conns, len(pool._used))
return conn
def release(self, conn):
self._pool.putconn(conn)
def close(self):
if hasattr(self, '_pool'):
self._pool.closeall()
__del__ = close
开发者ID:jampp,项目名称:macross-gcd,代码行数:22,代码来源:store.py
示例16: ConnectionPool
class ConnectionPool(object):
def __init__(self, conn_params, minconn=5, maxconn=5):
self._conn_params = conn_params.copy()
self._conn_params['minconn'] = minconn
self._conn_params['maxconn'] = maxconn
self._conn_pool = None
def initialize(self):
self._conn_pool = ThreadedConnectionPool(**self._conn_params)
@contextmanager
def cursor(self):
conn = self._conn_pool.getconn()
cursor = conn.cursor()
try:
yield cursor
conn.commit()
except Exception:
conn.rollback()
raise
finally:
self._conn_pool.putconn(conn)
开发者ID:RafaelSzefler,项目名称:rmq,代码行数:22,代码来源:connection.py
示例17: __init__
def __init__(self, db_config, table_raw=None, max_connections=10):
from psycopg2.pool import ThreadedConnectionPool
self.table_raw = table_raw
try:
self.pool = ThreadedConnectionPool(minconn=1,
maxconn=max_connections,
dsn="dbname={db_name} user={db_user} host={db_host} password={db_pass}"
.format(**db_config))
except Exception:
logger.exception("Error in db connection")
sys.exit(1)
logger.debug("Connected to database: {host}".format(host=db_config['db_host']))
开发者ID:xtream1101,项目名称:custom-utils,代码行数:14,代码来源:database.py
示例18: connect
def connect(self):
if self._connpool is not None:
return self
logger = logging.getLogger("database")
logger.info('connect to "%s"' % self.database_name)
host = CONFIG["db_host"] and "host=%s" % CONFIG["db_host"] or ""
port = CONFIG["db_port"] and "port=%s" % CONFIG["db_port"] or ""
name = "dbname=%s" % self.database_name
user = CONFIG["db_user"] and "user=%s" % CONFIG["db_user"] or ""
password = CONFIG["db_password"] and "password=%s" % CONFIG["db_password"] or ""
minconn = int(CONFIG["db_minconn"]) or 1
maxconn = int(CONFIG["db_maxconn"]) or 64
dsn = "%s %s %s %s %s" % (host, port, name, user, password)
self._connpool = ThreadedConnectionPool(minconn, maxconn, dsn)
return self
开发者ID:openlabs,项目名称:trytond,代码行数:15,代码来源:database.py
示例19: connect
def connect(self):
if self._connpool is not None:
return self
logger.info('connect to "%s"', self.database_name)
uri = parse_uri(config.get('database', 'uri'))
assert uri.scheme == 'postgresql'
host = uri.hostname and "host=%s" % uri.hostname or ''
port = uri.port and "port=%s" % uri.port or ''
name = "dbname=%s" % self.database_name
user = uri.username and "user=%s" % uri.username or ''
password = ("password=%s" % urllib.unquote_plus(uri.password)
if uri.password else '')
minconn = config.getint('database', 'minconn', default=1)
maxconn = config.getint('database', 'maxconn', default=64)
dsn = '%s %s %s %s %s' % (host, port, name, user, password)
self._connpool = ThreadedConnectionPool(minconn, maxconn, dsn)
return self
开发者ID:kret0s,项目名称:tryton3_8,代码行数:17,代码来源:database.py
示例20: __init__
def __init__(self,url=None,hstore=False,log=None,logf=None,min=1,max=5,
default_cursor=DictCursor):
params = urlparse.urlparse(url or
os.environ.get('DATABASE_URL') or
'postgres://localhost/')
self.pool = ThreadedConnectionPool(min,max,
database=params.path[1:],
user=params.username,
password=params.password,
host=params.hostname,
port=params.port,
)
self.hstore = hstore
self.log = log
self.logf = logf or (lambda cursor : cursor.query)
self.default_cursor = default_cursor
self.prepared_statement_id = 0
开发者ID:ephillipe,项目名称:pgwrap,代码行数:17,代码来源:db.py
注:本文中的psycopg2.pool.ThreadedConnectionPool类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论