来自 PostgreSQL docs在 BEGIN
上:
Issuing BEGIN when already inside a transaction block will provoke a warning message. The state of the transaction is not affected.
我怎样才能让 psycopg2
在出现任何此类警告时引发异常?
最佳答案
我远不是 psycopg2
或 Postgres
专家,而且,我确信有更好的解决方案来提高警告级别,但这是有效的对我来说 - 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/