为什么即使使用上下文管理器,aiomysql也会锁定表?

时间:2016-12-13 16:53:04

标签: aiohttp

我注意到即使我在"内执行sql语句,使用"上下文管理器,请求完成后,查询的表仍然被锁定,我无法执行"截断"直到我停止事件循环。

以下是我的代码示例:

import logging
import asyncio
import aiomysql
from aiohttp import web
from aiomysql.cursors import DictCursor


logging.basicConfig(level=logging.DEBUG)

async def index(request):
    async with request.app["mysql"].acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT * FROM my_table")
            lines = await cur.fetchall()

    return web.Response(text='Hello Aiohttp!')

async def get_mysql_pool(loop):
    pool = await aiomysql.create_pool(
        host="localhost",
        user="test",
        password="test",
        db="test",
        cursorclass=DictCursor,
        loop=loop
    )

    return pool

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    mysql = loop.run_until_complete(get_mysql_pool(loop))
    app = web.Application(loop=loop, debug=True)
    app["mysql"] = mysql
    app.router.add_get("/", index)
    web.run_app(app)

执行curl' http://localhost:8080/'后,我用mysql cli连接到mysql服务器并尝试执行" truncate my_table" - 它不会完成,直到我停止aiohttp。如何改变这种行为?

1 个答案:

答案 0 :(得分:2)

保持锁定,因为默认情况下连接不在 autocommit 模式下。添加autocommit=True可以解决问题。

pool = await aiomysql.create_pool(
    host="localhost",
    user="test",
    password="test",
    db="test",
    autocommit=True,
    cursorclass=DictCursor,
    loop=loop)

或者,可以通过显式命令释放事务:

await cur.execute("COMMIT;")

上下文管理器的主要目的是关闭 cursor ,而不是提交事务。

aiomysql 具有SQLAlchemy.core扩展,其中包含对事务的上下文管理器支持,请参见此处的示例:

https://github.com/aio-libs/aiomysql/blob/93aa3e5f77d77ad5592c3e9519cfc9f9587bf9ac/tests/pep492/test_async_with.py#L214-L234

相关问题