如何在 Django 中保证并发的数据一致性

前面一部分主要讲乐观锁和悲观锁。锁从数据库层面,保证了并发时的数据一致性。了解锁,有助于对并发解决方案的理解。后面一部分主要讲的是 Django 中,并发场景下,保证数据一致性的解决办法。

1. 关于锁

1.1 乐观锁

1
2
3
4
5
6
from django.db import transaction

@transaction.atomic
def viewfunc(request):
    1. This code executes inside a transaction.
    do_stuff()

2.2 部分函数 do_more_stuff() 开启事务。

1
2
3
4
5
6
7
8
9
from django.db import transaction

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

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

2.3 不要在事务中处理异常

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.db import transaction

def viewfunc(request):
    do_stuff()
    try:
        with transaction.commit_on_success():
            do_more_stuff_1() # in transaction
            try:
                do_more_stuff_2() # not in transaction
            except:
                pass
            do_more_stuff_3() # in transaction
    except:
        pass

4. 利用 select_for_update 函数