8

除了我的 python bot 之外,我还使用 Heroku 设置了一个 postgresql 服务器,它也在 heroku 上运行,但 bot 无法连接到数据库

我确保密码用户名等正确。

这是用于连接的方法:

async def create_db_pool():
    bot.pg_con = await asyncpg.create_pool(database="dbname", 
    user="username", 
    password="dbpw")

这就是我运行它的方式:

bot.loop.run_until_complete(create_db_pool())

预计将访问数据库并写入和读取数据,而不是我收到以下错误:

asyncpg.exceptions.ConnectionDoesNotExistError: connection was closed in the middle of operation
Task was destroyed but it is pending!
task: <Task pending coro=<chng_pr() running at I:/Python/HardCoreDisBot/Commands.py:38> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000002571E9B1978>()]>>
4

2 回答 2

2

max_inactive_connection_lifetime所以我查看了你的问题,发现了一个有类似问题的线程,他们似乎通过像这样输入他们的代码找到了解决方法。是该线程的链接。

async def create_db_pool():
    bot.pg_con = await asyncpg.create_pool(database="dbname", 
    user="username", 
    password="dbpw",
    max_inactive_connection_lifetime=3)
于 2020-11-07T11:45:51.900 回答
0

我对 Starlette 也有同样的问题。

根据我的发现,这里的问题是 asyncpg 不共享相同的异步循环。

我遵循了 asyncpg.create_pool(..., loop=asyncio.get_event_loop()) 的建议,虽然我本身并没有解决这个问题,但至少在刷新后重新建立了连接。

自从我写这篇文章以来,这似乎仍然是一个活跃的问题:https ://github.com/MagicStack/asyncpg/issues/309

Sanic 用户面临类似情况https://github.com/sanic-org/sanic/issues/152

编辑

这暂时对我有用:https ://magicstack.github.io/asyncpg/current/usage.html#connection-pools

async def handle(request):
"""Handle incoming requests."""
pool = request.app['pool']
power = int(request.match_info.get('power', 10))

# Take a connection from the pool.
async with pool.acquire() as connection:
    # Open a transaction.
    async with connection.transaction():
        # Run the query passing the request argument.
        result = await connection.fetchval('select 2 ^ $1', power)
        return web.Response(
            text="2 ^ {} is {}".format(power, result))
于 2021-02-19T15:17:18.380 回答