Django原子请求是如何工作的?

2024-05-20 17:10:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望我的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


Tags: thetodjangointestview视图objects
1条回答
网友
1楼 · 发布于 2024-05-20 17:10:18

原子请求是数据库连接设置dict的一个属性,而不是顶级设置。例如:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'ATOMIC_REQUESTS': True,
    }
}

相关问题 更多 >