通过psycopg2获取警告消息

时间:2014-12-01 20:31:57

标签: python postgresql psycopg2

我想通过psycopg2调用plpgsql函数并查看警告消息。 即,我有这个功能:

create or replace function test_warning() returns void as $$
begin
raise warning 'this is only a test';
end; 
$$
language plpgsql;

并在python中调用它:

import psycopg2
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.callproc("test_warning")
# or so:
cursor.execute('SELECT test_warning()')

不幸的是,plpgsql中定义的警告消息不会出现在python输出中的任何位置。 有没有办法在python输出中打印警告消息?

2 个答案:

答案 0 :(得分:10)

notices的{​​{1}}成员是发送到客户端的会话消息列表:

connection

http://initd.org/psycopg/docs/connection.html#connection.notices

要获得最后通知:

for notice in conn.notices:
    print notice

如果在函数内引发异常但未捕获,则不会收到警告。这是因为函数包装了一个隐式事务,并且该事务中的所有内容都被回滚,包括警告。

答案 1 :(得分:0)

我没有对Clodoaldo的答案发表评论的声誉,但是我获取最新通知(请注意查询可以生成多个通知)的解决方案非常简单:

def execute_query(query, conn):
    logger = logging.getLogger('test')
    nr_notices = len(conn.notices)
    cursor = conn.cursor()
    cursor.execute(query)
    for notice in conn.notices[nr_notices:]:
        logger.info(f'NOTICE: {notice}.')