如何在SQLAlchemy中将信息从会话传递到引擎事件before_cursor_execute和after_cursor_execute

时间:2019-11-28 09:09:06

标签: python sqlalchemy

我想记录每个用户执行的查询以及执行查询所花费的时间。为此,我遵循SQLAlchemy文档中的Performance部分,在该部分中,他们建议侦听这2个事件:

@event.listens_for(engine, "before_cursor_execute")
def before_cursor_execute(conn: Connection,
                          cursor: cursor,
                          statement: str,
                          parameters: dict,
                          context: PGExecutionContext_psycopg2,
                          executemany: bool
                          ):
    conn.info.setdefault('query_start_time', []).append(time.time())
    logger.debug("Start Query: %s", statement)


@event.listens_for(engine, "after_cursor_execute")
def after_cursor_execute(conn: Connection,
                         cursor: cursor,
                         statement: str,
                         parameters: dict,
                         context: PGExecutionContext_psycopg2,
                         executemany: bool
                         ):
    total = time.time() - conn.info['query_start_time'].pop(-1)
    logger.debug("Query Complete!")
    logger.debug("Total Time: %f ms", total)

我正在使用会话来处理查询,执行查询后可以看到日志。但是我想知道如何与事件监听器的任何参数共享用户。

0 个答案:

没有答案