django.db.transaction.TransactionManagementError

前一段时间在sentry上看到了这样一个错误“django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.”。这是我第一次看到这种类型的错误。看了一下报错的代码。

def buggy_code():
    with transaction.atomic():
            try:
                do_something()
            except:
                pass
            do_something2()

do_something()里面有数据库写操作,于是猜测数据库执行do_something()里的写操作时发生错误django抛了异常,但是被catch住了,代码走到do_something2()时进行数据库操作时,抛出了上述错误。
写了一小段代码验证猜想。

with transaction.atomic():
    try:
        UserBaseInfo.objects.filter(user_id=2).update(user_id=1)
    except Exception as e:
                print e
    print UserBaseInfo.objects.get(id=90)

在此代码执行前,数据库userbaseinfo这张表里已存在user_id=1的记录,并且该字段有唯一性限制。
运行之,报错django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block,和预想的一致。

总结一下,数据库在执行do_something()中的某一写操作时发生了错误。但是业务代码里try except捕获了异常但是没有将异常抛出,而是静默处理。代码顺利执行至do_something2(),在执行do_something2()中的数据库请求时,django向数据库发送rollback请求,并抛出异常。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,046评论 2 89
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • 1.衣着 印象深刻的一句话,要想让别人看到你的心灵美,首先也要让别人先能看到你。言外之意就是你的外表,决定了你们有...
    糖果_322c阅读 168评论 0 1
  • 高三毕业那一年的某一天,我在灶膛下面帮在做饭的母亲在添加柴火,母亲又跟我诉说,父亲的无能和自私。 我实在受不了母亲...
    漂流的傻子阅读 231评论 0 0
  • 一、学习与实践 1.付出不亚于任何人的努力 2.要谦虚,不要骄傲 3.要每天反省 4.活着,就要感谢 5.积善行,...
    Lucien光阅读 162评论 0 1