无法捕获SQLAlchemy IntegrityError

时间:2014-07-02 03:12:58

标签: python exception exception-handling error-handling sqlalchemy

尽我所能,我似乎无法正确捕捉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

更新

我发现了一些似乎适合这里发生的事情,在会话被刷新到数据库之后,并且在try / except块被执行之后,不会抛出完整性错误:{ {3}}

但是,在session.flush()块中添加try会产生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)

4 个答案:

答案 0 :(得分:20)

只要引发IntegrityError,无论您是否捕获到错误,您正在使用的会话都将失效。由于第二条错误消息指示您To begin a new transaction with this Session, first issue Session.rollback().继续使用会话,因此您需要发出session.rollback()

我不能肯定地说,但我猜你或你的web框架正在尝试继续使用以某种方式引发IntegrityError的会话。我建议您在发现异常后或session.rollback()函数中发出handle_elegantly

如果你运行以下内容,你会看到我的意思:

from sqlalchemy import types
from sqlalchemy import exc
from sqlalchemy import create_engine
from sqlalchemy.schema import Column
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()


class User(Base):
    __tablename__ = 'user'
    name = Column(types.String, primary_key=True)


def handle_elegantly(name):
    session = DBSession()
    session.add(User(name=name))
    session.flush()
    print 'Exception elegantly handled!!\n'


def pretend_view(request):
    """Pretend view in a Pyramid application using pyramid_tm"""
    session = DBSession()
    user = User()
    print '\n-------Here we rollback before continuing -------'
    try:
        session.add(user)
        session.flush()
    except exc.IntegrityError:
        session.rollback()
        handle_elegantly('This will run fine')

    print '\n------- Here we do not, and this will error -------'
    try:
        session.add(user)
        session.flush()
    except exc.IntegrityError:
        handle_elegantly('Exception will be raised')


if __name__ == '__main__':
    engine = create_engine('sqlite://')
    global DBSession
    DBSession = scoped_session(
        sessionmaker(extension=ZopeTransactionExtension()))
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all()
    pretend_view("dummy request")

答案 1 :(得分:19)

我在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 as e:
     db.session().rollback()

答案 2 :(得分:1)

您必须在发现错误后添加 session.rollback()

try:
    session.flush()
except IntegrityError:
    session.rollback()

答案 3 :(得分:-1)

SQLALCHEMY_COMMIT_ON_TEARDOWN = False