加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何防止在SQLAlchemy中更新/删除特定的类?

发布时间:2020-12-20 13:32:47 所属栏目:Python 来源:网络整理
导读:假设我有类Dog(),Walrus(),Boot(). 我想做它,所以你不能更新Walrus对象,虽然你可以删除它们,你永远不能删除Boot对象. 如果这样做: dog1 = Dog("DogName")walrus1 = Walrus("WalrusName")boot1 = Boot("BootName")session.add(dog1)session.add(walrus1)sess
假设我有类Dog(),Walrus(),Boot().
我想做它,所以你不能更新Walrus对象,虽然你可以删除它们,你永远不能删除Boot对象.
如果这样做:

dog1 = Dog("DogName")
walrus1 = Walrus("WalrusName")
boot1 = Boot("BootName")
session.add(dog1)
session.add(walrus1)
session.add(boot1)
session.flush()
transaction.commit()
dog1.name = "Fluffy"
walrus1.name = "Josh"
boot1.name = "Pogo"
session.flush()
transaction.commit()

它会在更改海象名称时引发异常,但允许更改其他名称.
如果我试图删除boot1,它会抛出异常.

我已经对事件听众进行了几次尝试,但我接近的两种方式并没有让我一路走到那里:

#One possibility
#I don't know how to tell that it's just an update though
#The is_modified seems to take inserts as well

@event.listens_for(Session,'before_flush')
def listener(thissession,flush_context,instances):
    for obj in thissession:
        if isinstance(obj,Walrus):
            if thissession.is_modified(obj,include_collections=False):
                thissession.expunge(obj)


#Possiblity two
#It says before_update but it seems to take in inserts as well
#Also documentation says it's not completely reliable to capture all statements
#where an update will occur
@event.listens_for(Walrus,'before_update',raw=True)
def pleasework(mapper,connection,target):
    print "nnInstance %s being updatednn" % target
    object_session(target).expunge(target)

编辑1:

@event.listens_for(Walrus,raw=True)
def prevent_walrus_update(mapper,target):
    print "nnInstance %s being updatednn" % target
    if target not None:
        raise

@event.listens_for(Boot,'before_delete',raw=True)
def prevent_boot_delete(mapper,target):
    print "nnInstance %s being deletednn" % target
    if target not None:
        raise

我有这个工作,它不允许我更新Walrus或删除Boot,但任何提示试图将崩溃与我似乎没有任何能力捕获的AttributeError.例如,如果我运行Walrus1.name =“Josh”然后在al处进行任何查询,即使是get,AttributeError也会使应用程序崩溃.我比我更进一步,但仍然相当不方便.

解决方法

您发布的第一个解决方案看起来应该可行,如果您只是将循环更改为:

for obj in thissession.dirty:

您可以使用相同的before_flush事件来阻止通过循环访问此对象来删除Boot对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读