通过psycopg2获取警告消息 [英] Get warning messages through psycopg2

查看:297
本文介绍了通过psycopg2获取警告消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to call a plpgsql function through psycopg2 and see the warning messages. I.e, I have this function:

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

并在python中这样称呼:

and call it so in 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输出中显示警告消息?

Unfortunately the warning message as defined in plpgsql does not appear anywhere in the python output. Is there a way to get the warning message printed in the python output?

推荐答案

连接的>通知成员是到目前为止发送给客户端的会话消息的列表:

The notices member of the connection is a list of the session's messages sent to the client up to that point:

for notice in conn.notices:
    print notice

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

要获取最新通知:

print conn.notices[-1]

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

If an exception is raised inside a function, and not caught, no warning will be received. That is because a function wraps an implicit transaction and everything inside that transaction is rolled back including warnings.

这篇关于通过psycopg2获取警告消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆