【问题标题】:How do I promote PostgreSQL warnings to exceptions in psycopg2?如何将 PostgreSQL 警告提升为 psycopg2 中的异常?
【发布时间】:2016-07-06 20:40:03
【问题描述】:

来自BEGIN上的PostgreSQL docs

当已经在事务块中时发出 BEGIN 将引发 警告信息。事务的状态不受影响。

如何让psycopg2 对任何此类警告提出异常?

【问题讨论】:

    标签: python postgresql warnings psycopg2


    【解决方案1】:

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

    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
    

    【讨论】:

    • 这看起来很干净。不过,如果 psycopg 开箱即用地支持此类游标,我们会很好。
    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    相关资源
    最近更新 更多