我希望我的Django视图是原子的。我是说,如果视图中有2个DB写操作,我希望0个写操作,或者2个写操作。
例如:
def test_view(request):
''' A test view from views.py '''
MyClass.objects.create()
raise Exception("whatever")
MyClass.objects.create()
我在文献中发现的似乎很有希望:
A common way to handle transactions on the web is to wrap each request in a transaction. Set ATOMIC_REQUESTS to True in the configuration of each database for which you want to enable this behavior.
It works like this. Before calling a view function, Django starts a transaction. If the response is produced without problems, Django commits the transaction. If the view produces an exception, Django rolls back the transaction.
但是,即使我设置了ATOMIC_REQUESTS = True
,在调用test_view()
时,也会创建第一个MyClass对象!我错过了什么?
注:我使用的是Django 1.7
原子请求是数据库连接设置dict的一个属性,而不是顶级设置。例如:
相关问题 更多 >
编程相关推荐