使用async / await

时间:2018-06-02 12:30:45

标签: python async-await tornado event-loop 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都是一个类,这导致了很多类/方法。

我习惯以阻塞的方式打开连接,然后使用包装器进行异步数据库调用,并关闭连接只关闭服务器,这种情况下最佳做法是{{1 }

1 个答案:

答案 0 :(得分:2)

在没有使用asyncpg的情况下,我假设在大多数符合asyncio的软件包中都有一个异步上下文管理器,可以准确地提供您所要求的内容。

类似的东西:

private void RetryLogSave(DynamicParameters parameters, int retries = 3)
{    
    int tries = 0;

    using (var connection = new SqlConnection(_connectionString))
    {
        connection.Open();

        using (var transaction = connection.BeginTransaction())
        {
            var logItemCommand = new CommandDefinition(commandText: Constants.InsertLogItem,
                parameters: parameters, transaction: transaction, commandType: System.Data.CommandType.Text);

            do
            {
                try
                {
                    tries++;
                    connection.Execute(logItemCommand);
                    transaction.Commit();
                    break;
                }
                catch (Exception exc)
                {
                    if (tries == retries)
                    {
                        transaction.Rollback();
                        throw exc;
                    }
                    Task.Delay(100 * tries).Wait();
                }
            }
            while (true);
        }
}
}

(取自this question

使用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__方法的类。

编辑1:

上面的例子部分来自我已经链接到的问题,部分是为了完整性而设计的。但是要解决你对with语句正在做什么的评论:

__aexit__

我不确定这是多么好的解释,也许你应该阅读context managers

相关问题