本文整理汇总了Python中asyncpg.create_pool方法的典型用法代码示例。如果您正苦于以下问题:Python asyncpg.create_pool方法的具体用法?Python asyncpg.create_pool怎么用?Python asyncpg.create_pool使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncpg
的用法示例。
在下文中一共展示了asyncpg.create_pool方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_bot
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def run_bot():
"""Launches the bot."""
log.info("Launching bot...")
loop = asyncio.get_event_loop()
pool: asyncpg.pool.Pool = loop.run_until_complete(create_pool(get_uri(), command_timeout=60))
if pool is None:
log.error('Could not set up PostgreSQL. Exiting.')
return
result = loop.run_until_complete(check_database(pool))
if not result:
log.error('Failed to check database')
return
bot = NabBot()
bot.pool = pool
bot.run()
示例2: on_ready
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def on_ready(self):
guild = self.bot.guilds[0]
if self.staff_role is None:
self.staff_role = guild.get_role(STAFF_ROLE_ID)
if self.fake_staff_role is None:
self.fake_staff_role = guild.get_role(FAKE_ROLE_ID)
self.bot.pool = await asyncpg.create_pool(
host=PostgreSQL.PGHOST,
port=PostgreSQL.PGPORT,
user=PostgreSQL.PGUSER,
password=PostgreSQL.PGPASSWORD,
database=PostgreSQL.PGDATABASE,
)
await self.migrate_quotes()
示例3: async_main
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def async_main(concurrency):
print(f'concurrency={concurrency}')
async with asyncpg.create_pool(
user='rssant', password='rssant',
database='rssant', host='127.0.0.1',
command_timeout=60, min_size=5, max_size=5
) as pool:
async with pool.acquire() as conn:
await init_table(conn)
await benchmark(
pool,
num_fid=1000,
num_round=3,
concurrency=concurrency,
)
await pool.close()
示例4: create_pool
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def create_pool(uri, **kwargs) -> asyncpg.pool.Pool:
"""Creates a connection pool to the specified PostgreSQL server"""
def _encode_jsonb(value):
return b'\x01' + json.dumps(value).encode('utf-8')
def _decode_jsonb(value):
return json.loads(value[1:].decode('utf-8'))
async def init(con):
await con.set_type_codec('jsonb', schema='pg_catalog', encoder=_encode_jsonb, decoder=_decode_jsonb,
format="binary")
try:
log.debug("Creating connection pool")
pool = await asyncpg.create_pool(uri, init=init, **kwargs)
except ValueError:
log.error("PostgreSQL error: Invalid URI, check postgresql.txt. "
"Format must be 'postresql://user:password@host/database'")
except asyncpg.PostgresError as e:
log.error(f"PostgreSQL error: {e}")
except TimeoutError:
log.error("PostgreSQL error: Connection timed out.")
except Exception as e:
log.error(f"Unexpected error: {e.__class__.__name__}: {e}")
else:
return pool
示例5: empty
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def empty():
"""Empties out the database.
Drops all tables and functions from the saved PostgreSQL database.
This action is irreversible, so use with caution."""
loop = asyncio.get_event_loop()
pool: asyncpg.pool.Pool = loop.run_until_complete(create_pool(get_uri(), command_timeout=60))
if pool is None:
log.error('Could not set up PostgreSQL. Exiting.')
return
db_name = loop.run_until_complete(get_db_name(pool))
confirm = click.confirm(f"You are about to drop all the tables and functions of the database '{db_name}'.\n"
"Are you sure you want to continue? This action is irreversible.")
if not confirm:
log.warning("Operation aborted.")
return
log.info("Clearing database...")
loop.run_until_complete(drop_tables(pool))
log.info("Database cleared")
示例6: create_pool
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def create_pool(*args,
dialect=None,
connection_class=_SAConnection,
**connect_kwargs):
class SAConnection(connection_class):
def __init__(self, *args, dialect=dialect, **kwargs):
super().__init__(*args, dialect=dialect, **kwargs)
connection_class = SAConnection
# dict is fine on the pool object as there is usually only one of them
# asyncpg.pool.Pool.__slots__ += ('__dict__',)
# monkey patch pool to have some extra methods
def transaction(self, **kwargs):
return ConnectionTransactionContextManager(self, **kwargs)
asyncpg.pool.Pool.transaction = transaction
asyncpg.pool.Pool.begin = transaction
pool = asyncpg.create_pool(*args, connection_class=connection_class,
**connect_kwargs)
return pool
示例7: connect
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def connect(self):
self._conn = await asyncpg.create_pool(user='root', password='root',
database='pokerpg', host='127.0.0.1')
# User functions
########################################################################
示例8: connect_to_db
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def connect_to_db(app: FastAPI) -> None:
logger.info("Connecting to {0}", repr(DATABASE_URL))
app.state.pool = await asyncpg.create_pool(
str(DATABASE_URL),
min_size=MIN_CONNECTIONS_COUNT,
max_size=MAX_CONNECTIONS_COUNT,
)
logger.info("Connection established")
示例9: connect_redis
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def connect_redis(self):
self.redis = await aioredis.create_pool("redis://localhost", minsize=5, maxsize=10, loop=self.loop, db=0)
info = (await self.redis.execute("INFO")).decode()
for line in info.split("\n"):
if line.startswith("redis_version"):
self.redis_version = line.split(":")[1]
break
示例10: connect_postgres
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def connect_postgres(self):
self.pool = await asyncpg.create_pool(**self.config.database, max_size=20, command_timeout=60)
示例11: message_loop
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def message_loop(self):
try:
if self.dsn:
self.db = await asyncpg.create_pool(dsn=self.dsn, min_size=1, max_size=1)
self.reader = await self.get_pipe_reader(self.in_reader)
self.writer = await self.get_pipe_writer(self.out_writer)
while True:
msg_type, msg = await self.pipe_get_msg(self.reader)
if msg_type == b'pipe_read_error':
return
if msg_type == b'get':
self.loop.create_task(self.load_blocks(bytes_to_int(msg), self.rpc_batch_limit))
continue
if msg_type == b'rpc_batch_limit':
self.rpc_batch_limit = bytes_to_int(msg)
continue
if msg_type == b'target_height':
self.target_height = bytes_to_int(msg)
continue
except:
pass
示例12: get_poll
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def get_poll(self) -> asyncpg.pool.Pool:
if not self.poll:
self.poll = await asyncpg.create_pool('postgresql://duckhunt:duckhunt@localhost/dhv3')
return self.poll
示例13: _get_pool
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def _get_pool(self):
if not self._pool:
self._pool = await asyncpg.create_pool(
self.dsn,
min_size=self.pool_size,
max_size=self.pool_size
)
return self._pool
示例14: run_aiopg
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def run_aiopg():
pool = await aiopg.create_pool(dsn, minsize=5, maxsize=5)
t0 = time.time()
for i in range(1000):
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT 1")
ret = []
async for row in cur:
ret.append(row)
assert ret == [(1,)]
print('run_aiopg', time.time() - t0)
pool.close()
await pool.wait_closed()
示例15: run_asyncpg
# 需要导入模块: import asyncpg [as 别名]
# 或者: from asyncpg import create_pool [as 别名]
def run_asyncpg():
async with asyncpg.create_pool(
user='rssant', password='rssant',
database='rssant', host='127.0.0.1',
command_timeout=60, min_size=5, max_size=5
) as pool:
t0 = time.time()
for i in range(1000):
async with pool.acquire() as conn:
values = await conn.fetch("SELECT 1")
assert values == [(1,)]
print('run_asyncpg', time.time() - t0)
await pool.close()