當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。