删除时无法捕获SQLAlchemy IntegrityError

时间:2015-12-01 14:50:04

标签: python sqlalchemy pyramid

我知道关于完全相同的问题还有很多其他问题,但是我已经尝试了他们的答案,到目前为止还没有一个工作。

我试图从与其他表有关系的表中删除记录。这些表中的外键是nullable=false,因此尝试删除另一个表正在使用的记录应引发异常。

但即使用cat try-except包围delete语句,错误仍然没有被捕获,所以我怀疑异常可能会在其他地方引发。

我在Pyramid框架中使用SQLite和SQLAlchemy,并且我的会话配置了ZopeTransactionExtension

这就是我尝试删除的方式: 在views.py

from sqlalchemy.exc import IntegrityError
from project.app.models import (
    DBSession,
    foo)

@view_config(route_name='fooview', renderer='json', permission='view')
def fooview(request):
    """ The fooview handles different cases for foo
        depending on the http method
    """
    if request.method == 'DELETE':
        if not request.has_permission('edit'):
            return HTTPForbidden()

        deleteid = request.matchdict['id']
        deletethis = DBSession.query(foo).filter_by(id=deleteid).first()

        try:
           qry = DBSession.delete(deletethis)
           transaction.commit()
           if qry == 0:
               return HTTPNotFound(text=u'Foo not found')
       except IntegrityError:
           DBSession.rollback()
           return HTTPConflict(text=u'Foo in use')

        return HTTPOk()

在models.py中,我设置了DBSession和我的模型:

from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    relationship,
    backref,
)

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension('changed')))
Base = declarative_base()

class foo(Base):
    """ foo defines a unit used by bar
    """
    __tablename__ = 'foo'
    id = Column(Integer, primary_key=True)
    name = Column(Text(50))

    bars = relationship('bar')

class bar(Base):
    __tablename__ = 'bar'
    id = Column(Integer, primary_key=True)
    fooId = Column(Integer, ForeignKey('foo.id'), nullable=False)

    foo = relationship('foo')

在__init__.py中我配置了我的会话:

from project.app.models import (
    DBSession,
    Base,
)

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    # fix for association_table cascade delete issues
    engine.dialect.supports_sane_rowcount = engine.dialect.supports_sane_multi_rowcount = False
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine

使用此设置我

  

IntegrityError:(IntegrityError)NOT NULL约束失败

追溯here

如果我将transaction.commit()替换为DBSession.flush(),我会

  

ResourceClosedError:此事务已关闭

如果我删除transaction.commit(),我仍然会收到相同的错误,但没有明确的起源点。

更新: 我进行了一些鼻子测试,在某些情况下,但不是全部,但是正确处理了异常。

在我的测试中,我导入会话并对其进行配置:

from optimate.app.models import (
    DBSession,
    Base,
    foo)

def _initTestingDB():
    """ Build a database with default data
    """
    engine = create_engine('sqlite://')
    Base.metadata.create_all(engine)
    DBSession.configure(bind=engine)
    with transaction.manager:
        # add test data

class TestFoo(unittest.TestCase):
    def setUp(self):
        self.config = testing.setUp()
        self.session = _initTestingDB()

    def tearDown(self):
        DBSession.remove()
        testing.tearDown()

    def _callFUT(self, request):
        from project.app.views import fooview
        return fooview(request)

    def test_delete_foo_keep(self):
        request = testing.DummyRequest()
        request.method = 'DELETE'
        request.matchdict['id'] = 1
        response = self._callFUT(request)
        # foo is used so it is not deleted
        self.assertEqual(response.code, 409)

    def test_delete_foo_remove(self):
        _registerRoutes(self.config)
        request = testing.DummyRequest()
        request.method = 'DELETE'
        request.matchdict['id'] = 2
        response = self._callFUT(request)
        # foo is not used so it is deleted
        self.assertEqual(response.code, 200)

有谁知道发生了什么?

2 个答案:

答案 0 :(得分:2)

你可能只是“做错了”。您的问题涉及两个问题。处理由数据库完整性错误引发的事务级错误,并为应用程序代码/模型/查询建模以实现业务逻辑。我的回答重点是编写符合常见模式的代码,同时使用pyramid_tm进行事务管理,将sqlalchemy用作ORM。

在金字塔中,如果您已配置会话(脚手架自动为您执行)以使用ZopeTransactionExtension,则在视图执行之后才会刷新/提交会话。 如果您想在视图中自己捕获任何SQL错误,则需要强制刷新以将SQL发送到引擎。 DBSession.flush()应该在delete(...)之后执行。

如果你提出任何4xx / 5xx HTTP返回码,例如金字塔例外HTTPConflict,交易将被中止。

@view_config(route_name='fooview', renderer='json', permission='view')
def fooview(request):
    """ The fooview handles different cases for foo
        depending on the http method
    """
    if request.method == 'DELETE':
        if not request.has_permission('edit'):
            return HTTPForbidden()

        deleteid = request.matchdict['id']
        deletethis = DBSession.query(foo).filter_by(id=deleteid).first()
        if not deletethis:
            raise HTTPNotFound()

        try:
           DBSession.delete(deletethis)
           DBSession.flush()
        except IntegrityError as e:
           log.debug("delete operation not possible for id {0}".format(deleteid)
           raise HTTPConflict(text=u'Foo in use')

        return HTTPOk()

excerpt from todopyramid/models.py突出显示了如何在不使用DBSession对象的情况下删除集合项。

def delete_todo(self, todo_id):
    """given a todo ID we delete it is contained in user todos 

    delete from a collection
    http://docs.sqlalchemy.org/en/latest/orm/session.html#deleting-from-collections
    https://stackoverflow.com/questions/10378468/deleting-an-object-from-collection-in-sqlalchemy"""
    todo_item = self.todo_list.filter(
            TodoItem.id == todo_id)

    todo_item.delete()

这个sample code from pyramid_blogr清楚地显示了删除SQL数据库项目的简单金字塔视图代码的外观。通常您不必与事务进行交互。这是一项功能 - 广告为one the unique feature of pyramid。只需选择任何使用sqlalchemy的金字塔教程,并尽可能地坚持使用模式。如果您在应用程序模型级别解决问题,则事务机制将隐藏在后台,除非您明确需要其服务。

@view_config(route_name='blog_action', match_param="action=delete", permission='delete')
def blog_delete(request):
    entry_id = request.params.get('id', -1)
    entry = Entry.by_id(entry_id)
    if not entry:
        return HTTPNotFound()
    DBSession.delete(entry)
    return HTTPFound(location=request.route_url('home'))

要向应用程序用户提供有意义的错误消息,您可以在数据库模型层或金字塔视图层捕获数据库约束的错误。捕获sqlalchemy异常以提供错误消息可能与此sample code

类似
from sqlalchemy.exc import OperationalError as SqlAlchemyOperationalError

@view_config(context=SqlAlchemyOperationalError)
def failed_sqlalchemy(exception, request):
    """catch missing database, logout and redirect to homepage, add flash message with error

    implementation inspired by pylons group message 
    https://groups.google.com/d/msg/pylons-discuss/BUtbPrXizP4/0JhqB2MuoL4J
    """
    msg = 'There was an error connecting to database'
    request.session.flash(msg, queue='error')
    headers = forget(request)

    # Send the user back home, everything else is protected  
    return HTTPFound(request.route_url('home'), headers=headers)

参考

答案 1 :(得分:1)

不确定这是否有帮助 - 我没有从追溯中捕获出错的地方,需要更多时间。但您可以像这样使用事务管理器:

from sqlalchemy.exc import IntegrityError


try:
   with transaction.manager:
        deletethis = DBSession.query(foo).filter_by(id=deleteid).first()
        qry = DBSession.delete(deletethis)
        if qry == 0:
            return HTTPNotFound()
    # transaction.manager commits when with context manager exits here
except IntegrityError:
   DBSession.rollback()
   return HTTPConflict()

return HTTPOk()