0

这是我Database班上的一些相关代码:

class Database:

    pool = None

    def __init__(self, dsn):
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.init_async(dsn))

    async def init_async(self, dsn):
        Database.pool = await asyncpg.create_pool(dsn)

    async def get_connection(self):
        return await Database.pool.acquire()

我认为类上的静态属性将是存储连接池的理想方式,以前我每个类实例都有一个池,有点打败池的对象。get_connection我现在在以下代码中调用错误:

async def field(self, sql, *values):
    async with await self.get_connection() as conn:
        return await conn.fetchval(sql, *values)

回溯如下:

Traceback (most recent call last):
  File "D:\ProgramData\Anaconda3\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\Personal\Python Projects\MusicBot\src\bot\bot.py", line 71, in on_message
    await self.process_commands(msg)
  File "D:\Personal\Python Projects\MusicBot\src\bot\bot.py", line 65, in process_commands
    ctx = await self.get_context(msg, cls=commands.Context)
  File "D:\ProgramData\Anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 852, in get_context
    prefix = await self.get_prefix(message)
  File "D:\ProgramData\Anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 797, in get_prefix
    ret = await discord.utils.maybe_coroutine(prefix, self, message)
  File "D:\ProgramData\Anaconda3\lib\site-packages\discord\utils.py", line 331, in maybe_coroutine
    return await value
  File "D:\Personal\Python Projects\MusicBot\src\bot\bot.py", line 61, in prefix
    prefix = await self._fetch_prefix(msg)
  File "D:\Personal\Python Projects\MusicBot\src\bot\bot.py", line 75, in _fetch_prefix
    prefix = await self.db.field("SELECT cmd_prefix FROM guild WHERE guild_id = $1", id)
  File "D:\Personal\Python Projects\MusicBot\src\db\database.py", line 35, in field
    async with await self.get_connection() as conn:
AttributeError: __aexit__

看来我get_connection的过敏了async with。如果我async with用普通替换,await那么东西会再次起作用:

async def field(self, sql, *values):
    conn = await self.get_connection()
    return await conn.fetchval(sql, *values)

我得到一个属性错误这里有什么问题__aexit__

我被提到了这个问题,但我无法“适应”问题中的代码结构和我的场景的给定答案。

4

0 回答 0