我希望通过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输出中打印警告消息吗?
发布于 2014-12-01 23:08:02
notices成员的connection是发送到客户端的会话消息的列表:
for notice in conn.notices:
print noticehttp://initd.org/psycopg/docs/connection.html#connection.notices
为了得到最后的通知:
print conn.notices[-1]如果在函数中引发异常,但未捕获异常,则不会收到警告。这是因为一个函数包装一个隐式事务,事务中的所有内容都回滚,包括警告。
发布于 2018-12-05 09:53:27
我没有资格对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}.')https://stackoverflow.com/questions/27236749
复制相似问题