以下是一些演示设置的示例代码:
from sqlalchemy import Column, Integer, CheckConstraint
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Model(Base):
__tablename__ = 'model'
id = Column(Integer, primary_key=True)
a = Column(Integer, nullable=False)
b = Column(Integer, nullable=False)
__table_args__ = (
CheckConstraint('a != b', name='not_equal'),
CheckConstraint('a != 1', name='not_one'),
)
engine = create_engine(...)
Base.metadata.create_all(engine)
以下是一个演示,即将约束失败的模型添加到事务中的session
只会抛出IntegrityError
:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import IntegrityError
engine = create_engine(...)
session = sessionmaker(bind=engine, autocommit=True)()
try:
with session.begin():
model = Model()
model.a = 1
model.b = 2
session.add(model)
except IntegrityError as e:
print(e)
try:
with session.begin():
model = Model()
model.a = 2
model.b = 2
session.add(model)
except IntegrityError as e:
print(e)
我知道一旦我抓住它就可以提取IntegrityError
的详细信息,以便我可以提出自己的异常。
我无法弄清楚如何处理IntegrityError
处于足够低的水平,而我的实际应用逻辑不必处理它。换句话说,我更喜欢允许像
try:
with session.begin():
model = Model()
model.a = 1
model.b = 2
session.add(model)
except NotOneError as e:
print(e)
我是否可以通过某种方式将错误包装代码附加到模型定义或会话中?