python – 使用async / await打开/关闭数据库连接的最佳方法
作者:互联网
在我发现的教程中,每个请求总是打开和关闭连接,例如:
import asyncio
import asyncpg
async def run():
conn = await asyncpg.connect(user='user', password='password',
database='database', host='127.0.0.1')
values = await conn.fetch('''SELECT * FROM mytable''')
await conn.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
虽然这适用于单个功能,但Web应用程序如何?
IE:例如在Tornado中,每个URL都是一个类,这导致了很多类/方法.
我习惯以阻塞的方式打开连接,然后使用包装器进行异步数据库调用,并关闭连接只关闭服务器,在这种情况下使用async / await的最佳做法是什么?
解决方法:
如果没有使用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)
(摘自this question)
使用async with statements检查上下文管理器或示例的文档,或者如果没有其他内容,则检查源代码中已实现__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()
我不确定这是多么好的解释,也许你应该在context managers读到.
标签:event-loop,python,async-await,tornado,asyncpg 来源: https://codeday.me/bug/20190910/1798530.html