当前位置: 首页>>代码示例>>Python>>正文


Python asyncpg.create_pool方法代码示例

本文整理汇总了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() 
开发者ID:NabDev,项目名称:NabBot,代码行数:20,代码来源:launcher.py

示例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() 
开发者ID:CyberDiscovery,项目名称:cyberdisc-bot,代码行数:20,代码来源:fun.py

示例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() 
开发者ID:anyant,项目名称:rssant,代码行数:18,代码来源:benchmark_postgresfs.py

示例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 
开发者ID:NabDev,项目名称:NabBot,代码行数:27,代码来源:launcher.py

示例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") 
开发者ID:NabDev,项目名称:NabBot,代码行数:24,代码来源:launcher.py

示例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 
开发者ID:CanopyTax,项目名称:asyncpgsa,代码行数:24,代码来源:pool.py

示例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
    ######################################################################## 
开发者ID:henry232323,项目名称:RPGBot,代码行数:8,代码来源:db.py

示例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") 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:12,代码来源:events.py

示例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 
开发者ID:CHamburr,项目名称:modmail,代码行数:9,代码来源:bot.py

示例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) 
开发者ID:CHamburr,项目名称:modmail,代码行数:4,代码来源:bot.py

示例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 
开发者ID:bitaps-com,项目名称:pybtc,代码行数:28,代码来源:block_loader.py

示例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 
开发者ID:DuckHunt-discord,项目名称:DHV3,代码行数:7,代码来源:database_postgres.py

示例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 
开发者ID:mfussenegger,项目名称:cr8,代码行数:10,代码来源:clients.py

示例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() 
开发者ID:anyant,项目名称:rssant,代码行数:16,代码来源:benchmark_asyncio_postgres.py

示例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() 
开发者ID:anyant,项目名称:rssant,代码行数:15,代码来源:benchmark_asyncio_postgres.py


注:本文中的asyncpg.create_pool方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。