- 我想避免
errorCount += 1
在多个地方写作。 - 我正在寻找比
成功 = 假 尝试: ... 别的: 成功 = 真 最后: 如果成功: storage.store.commit() 别的: storage.store.rollback()
- 我试图避免
store.rollback()
在每个 except 子句中。
关于如何做到这一点的任何想法?
count = 0
successCount = 0
errorCount = 0
for row in rows:
success = False
count += 1
newOrder = storage.RepeatedOrder()
storage.store.add(newOrder)
try:
try:
newOrder.customer = customers[row.customer_id]
except KeyError:
raise CustomerNotFoundError, (row.customer_id,)
newOrder.nextDate = dates[row.weekday]
_fillOrder(newOrder, row.id)
except CustomerNotFoundError as e:
errorCount += 1
print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id)
except ProductNotFoundError as e:
errorCount += 1
print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id)
else:
success = True
successCount += 1
finally:
if success:
storage.store.commit()
else:
storage.store.rollback()
print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount)