Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Django 事务 #5

Open
sfPPP opened this issue Mar 30, 2018 · 0 comments
Open

Django 事务 #5

sfPPP opened this issue Mar 30, 2018 · 0 comments

Comments

@sfPPP
Copy link
Owner

sfPPP commented Mar 30, 2018

它是这样工作的:当有请求过来时,Django会在调用视图方法前开启一个事务。如果请求却正确处理并正确返回了结果,Django就会提交该事务。否则,Django会回滚该事务。
with transaction.atomic():
下面的代码支持事务

下面是被当做上下文管理器来使用:

from django.db import transaction

def viewfunc(request):
# This code executes in autocommit mode (Django's default).
do_stuff()

with transaction.atomic():
    # This code executes inside a transaction.
    do_more_stuff()

一旦把atomic代码块放到try/except中,完整性错误就会被自然的处理掉了,比如下面这个例子:

from django.db import IntegrityError, transaction

@transaction.atomic
def viewfunc(request):
create_parent()

try:
    with transaction.atomic():
        generate_relationships()
except IntegrityError:
    handle_exception()

add_children()

这个例子中,即使generate_relationships()中的代码打破了数据完整性约束,你仍然可以在add_children()中执行数据库操作,并且create_parent()产生的更改也有效。需要注意的是,在调用handle_exception()之前,generate_relationships()中的修改就已经被安全的回滚了。因此,如果有需要,你照样可以在异常处理函数中操作数据库。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant