python - 如何将 PostgreSQL 警告提升为 psycopg2 中的异常?

标签 python postgresql warnings psycopg2

来自 PostgreSQL docsBEGIN 上:

Issuing BEGIN when already inside a transaction block will provoke a warning message. The state of the transaction is not affected.

我怎样才能让 psycopg2 在出现任何此类警告时引发异常?

最佳答案

我远不是 psycopg2Postgres 专家,而且,我确信有更好的解决方案来提高警告级别,但这是有效的对我来说 - a custom cursor调查 connection notices而且,如果那里有东西 - 它会抛出异常。实现本身主要用于教育目的 - 我确信它需要进行调整以适应您的用例:

import psycopg2

# this "cursor" class needs to be used as a base for custom cursor classes
from psycopg2.extensions import cursor  

class ErrorThrowingCursor(cursor):
    def __init__(self, conn, *args, **kwargs):
        self.conn = conn
        super(ErrorThrowingCursor, self).__init__(*args, **kwargs)

    def execute(self, query, vars=None):
        result = super(ErrorThrowingCursor, self).execute(query, vars)

        for notice in self.conn.notices:
            level, message = notice.split(": ")
            if level == "WARNING":
                raise psycopg2.Warning(message.strip())

        return result

使用示例:

conn = psycopg2.connect(user="user", password="secret")
cursor = conn.cursor(conn, cursor_factory=ErrorThrowingCursor)

如果在查询执行后发出警告,这将引发异常(psycopg2.Warning 类型)。示例:

psycopg2.Warning: there is already a transaction in progress

关于python - 如何将 PostgreSQL 警告提升为 psycopg2 中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38233400/

相关文章:

python - 使用 for 循环在 django 模板中显示值

Python 实例化子类

sql - 如何从所有模式中删除函数

asp.net - 如何有选择地抑制 Visual Studio 中的标记验证?

python - 如何检查一个字符串中的两个连续值是否是另一个字符串中的字符

python - 将多个子字符串匹配模式提取到列中

PostgreSQL 在一行中查看同一表的一组相关记录

sql - 带有 CASE 语句的 PostgreSQL 慢连接

python - python 是否像 perl 中那样有 "use strict;"和 "use warnings;"?

c# - 如果我不注意警告 "hides inherited member. To make the current member override that implementation...."怎么办