使用stmt.compile打印查询时如何禁止SQLAlchemy警告?

时间:2017-03-06 20:33:30

标签: python python-2.7 sqlalchemy

我想记录我想要调试它们的事件中发生的所有查询,或者稍后对它们运行解释计划。

例如:

from sqlalchemy import select
from sqlalchemy.dialect import oracle
queries = {}
# ...
sel = select([foo.c.id, foo.c.bar])
queries['foo query'] = sel.compile(dialect=oracle.dialect(), 
                                   compile_kwargs={'literal_binds': True})
results = conn.execute(select)

这总是会输出以下警告:

SAWarning: Textual column expression 'id' should be explicitly declared
 with text('location'), or use column('location') for more specificity (this
 warning may be suppressed after 10 occurrences)
if guess_is_literal else "column"

有没有办法抑制这些警告?值得注意的是,我只想在记录/打印查询的特定情况下抑制它们,而不是全局抑制。

1 个答案:

答案 0 :(得分:0)

您可以在Python 2.7中禁止SQL Alchemy警告消息,如下所示:

import warnings
from sqlalchemy import exc as sa_exc

with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=sa_exc.SAWarning)
    results = query.execute()