gpt4 book ai didi

python - 无法捕获 SQLAlchemy IntegrityError

转载 作者:IT老高 更新时间:2023-10-28 22:18:16 25 4
gpt4 key购买 nike

尽我所能,我似乎无法正确捕捉到 sqlalchemy IntegrityError:

from sqlalchemy import exc

try:
insert_record()
except exc.IntegrityError, exc:
print exc # this is never called
handle_elegantly() # this is never called

正如人们所期望的那样:

IntegrityError: (IntegrityError) insert or update on table "my_table" 
violates foreign key constraint "my_table_some_column_fkey"

我已尝试明确:

from sqlalchemy.exc import IntegrityError

更新:

我发现一些似乎适合这里发生的事情,在 session 刷新到数据库之前不会引发完整性错误,并且在 try/except 之后 block 已被执行:Trying to catch integrity error with SQLAlchemy

但是,在 try block 中添加 session.flush() 会产生 InvalidRequestError:

ERROR:root:This Session's transaction has been rolled back due to a previous 
exception during flush. To begin a new transaction with this Session,
first issue Session.rollback().
Original exception was: (IntegrityError)

最佳答案

我的 Flask 应用程序也有同样的需求,我按如下方式处理它并且它可以工作:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import exc

db = SQLAlchemy(Flask(__name__))

try:
db.session.add(resource)
return db.session.commit()
except exc.IntegrityError:
db.session.rollback()

关于python - 无法捕获 SQLAlchemy IntegrityError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24522290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com