在没有使用 asyncpg 的情况下,我假设在大多数兼容 asyncio 的包中都有一个异步上下文管理器,可以完全满足您的要求。
就像是:
async with asyncpg.create_pool(**kwargs) as pool:
async with pool.acquire() as connection:
async with connection.transaction():
result = await connection.fetchval(fetch stuff)
connection.execute(insert stuff with result)
(取自这个问题)
检查文档中是否提及上下文管理器或带有async with
语句的示例,或者如果没有其他内容,请检查源代码中实现__aenter__
,__aexit__
方法的类。
编辑1:
上面的例子部分取自我所链接的问题,部分是为了完整性而设计的。但是要解决您对 with 语句正在做什么的评论:
async with asyncpg.create_pool(**kwargs) as pool:
#in this block pool is created and open
async with pool.acquire() as connection:
# in this block connection is acquired and open
async with connection.transaction():
# in this block each executed statement is in a transaction
execute_stuff_with_connection(connection)
# now we are back up one logical block so the transaction is closed
do_stuff_without_transaction_but_with_connection(connection)
# now we are up another block and the connection is closed and returned to the pool
do_more_stuff_with_pool(pool)
# now we are up another level and the pool is closed/exited/cleaned up
done_doing_async_stuff()
我不确定这是多么好的解释,也许您应该阅读上下文管理器。