ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

python – 使用async / await打开/关闭数据库连接的最佳方法

2019-09-10 11:55:13  阅读:326  来源: 互联网

标签:event-loop python async-await tornado asyncpg


在我发现的教程中,每个请求总是打开和关闭连接,例如:

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有