如何避免/修复django的DatabaseTransactionError

时间:2015-08-24 14:47:37

标签: python django django-orm

我有以下(释义)代码符合竞争条件:

data = np.genfromtxt("/home/.../.../.../all", delimiter=',', skip_header=True)

model = data[:,0]
fhr = data[:,1]
lats = data[:,2]
lons = data[:,3]

models = ['ANVI', 'BAMS', 'CLIP']
cols = ['r','g','b']

for i in range(len(models)):
    plt.plot(x[model==models[i]],y[model==models[i]],
             marker='o',linestyle='-',color=cols[i])
plt.show()

它引发了一个DatabaseTransactionError:

def calculate_and_cache(template, template_response):
    # run a fairly slow and intensive calculation:
    calculated_object = calculate_slowly(template, template_response)
    cached_calculation = Calculation(calculated=calculated_object,
                                     template=template,
                                     template_response=template_response)
    # try to save the calculation just computed:
    try:
        cached_calculation.save()
        return cached_calculation
    # if another thread beat you to saving this, catch the exception
    # but return the object that was just calculated
    except DatabaseError as error:
        log(error)
        return cached_calculation

The docs有关于DTE的说法:

当退出原子块时,Django会查看它是正常退出还是有异常来确定是提交还是回滚....如果你在回滚发生之前尝试运行数据库查询,Django会提高一个TransactionManagementError。

they也有这个,对它们说得更加模糊:

针对与数据库事务相关的所有问题引发TransactionManagementError。

我的问题,按照普遍性递增的顺序:

  1. 通过让TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. 优雅地退出并仍然返回对象,捕获DatabaseError实际上是否解决了竞争条件?
  2. 原子块在上面的代码中从哪里开始,它在哪里结束?
  3. 我做错了什么,我该如何解决?

0 个答案:

没有答案