【问题标题】:Is it possible to count the number of SQL queries with Flask / SQLAlchemy / Pytest / SQLite?是否可以使用 Flask / SQLAlchemy / Pytest / SQLite 计算 SQL 查询的数量?
【发布时间】:2020-12-22 15:52:46
【问题描述】:

我有一个使用 SQLAlchemy 和数据库的 Flask 项目。为了测试,我将数据库替换为 SQLite 数据库。

现在我想运行一些视图并测试执行的查询数量。本质上,我想避免意外遇到 (n+1) 选择问题。是否可以从 SQLite 或 Pytest / Flask 插件获取执行的 SQL 查询的数量?

【问题讨论】:

标签: python sqlalchemy select-n-plus-1


【解决方案1】:

您可以通过https://docs.sqlalchemy.org/en/13/core/events.html(记录事件)来做到这一点

event.listen(engine, "before_cursor_execute")

现在您可以使用文档中提到的功能了:

    @event.listens_for(conn, 'before_cursor_execute')
    def before_cursor_execute(conn, cursor, statement, parameters,
                                    context, executemany):
        log.info("Received statement: %s", statement)```

【讨论】:

    猜你喜欢
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2017-10-11
    • 2020-03-25
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多