python - 删除时无法捕获 SQLAlchemy IntegrityError

标签 python sqlalchemy pyramid

我知道还有许多其他问题与完全相同的问题有关,但我已经尝试过他们的答案,但到目前为止没有一个有效。

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

但即使使用包罗万象的删除语句 try-except错误仍然没有被捕获,所以我怀疑异常可能是在其他地方引发的。

我在 Pyramid 框架中使用 SQLite 和 SQLAlchemy,并且我的 session 配置为 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 中,我像这样配置 session :

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 constraint failed

回溯here .

如果我替换transaction.commit()DBSession.flush() ,我明白

ResourceClosedError: This transaction is closed

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

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

在我的测试中,我导入 session 并配置它:

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)

有谁知道这是怎么回事吗?

最佳答案

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

在 Pyramid 中,如果您已将 session (脚手架自动为您执行)配置为使用 ZopeTransactionExtension,则在 View 执行之前 session 不会刷新/提交。 如果您想自己捕获 View 中的任何 SQL 错误,则需要强制刷新以将 SQL 发送到引擎。 DBSession.flush() 应该在删除(...)之后执行。

如果您引发任何 4xx/5xx HTTP 返回代码,例如 Pyramid 异常 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 数据库项目的简单 Pyramid View 代码是什么样子。通常您不必与事务交互。这是一项功能 - 正如广告中所述 one the unique feature of pyramid 。只需选择任何使用 sqlalchemy 的可用 Pyramid 教程,并尝试尽可能坚持这些模式。如果您在应用程序模型级别解决问题,事务机制将隐藏在后台,除非您明确需要其服务。

@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'))

为了向应用程序用户提供有意义的错误消息,您可以在数据库模型层或 Pyramid View 层捕获数据库约束上的错误。捕获 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)

引用文献

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

相关文章:

python - 在将实体保存到 ndb 之前通过其键引用实体

python - 无法捕获 Flask 应用程序中的 _mysql_exceptions.OperationalError

python - Sqlalchemy远程数据库 session 刷新/刷新问题

python - sqlalchemy 动态映射

python - pyramid_mailer 不发送电子邮件?

python - 在 Pyramid 中创建动态类 View

python - 用 C 编写的函数真的不能有 **kwargs 参数吗?

python - 保留第一个非零元素,将所有其他元素设置为 0

python - Tastypie apply_filters 具有不同的

python - Pyramid:用于自定义记录器和外部授权系统的 Tween 或 WSGI 中间件?