Django ORM 2 - Database transactions
Default behavior và transaction trong HTTP request
-
Default transaction behavior của Django: Tự động commit tới database đối với mỗi câu query trừ khi transaction được active.
-
Set
ATOMIC_REQUESTS
bằng True để bọc HTTP request trong một transaction. Cách thức hoạt động: Bắt đầu call view function, một transaction được khởi tạo, nếu view function không xảy ra lỗi, transaction được commit nếu không sẽ bị rollback. -
Có thể tạo substraction bằng cách sử dụng automic() context manager. Tuy nhiên tới cuối view function, tất cả sẽ được commit.
-
Chú ý: tạo transaction tại mỗi view function có thể dẫn tới giảm performance khi có nhiều request cùng lúc. Performance bị ảnh hưởng nhiều hay ít tuỳ vào câu query trong view function hoặc cách database handle lock.
Controlling transactions explicitly
Django có duy nhất một API để control transaction một cách tường minh: atomic(using=None, savepoint=True, durable=False)
atomic()
đinh nghĩa một block of code, nếu thực thi thành công, những thay đổi trong transaction được commit tới database, nếu có exception xảy ra, toàn bộ thay đổi sẽ bị rollback.
-
atomic()
có thể được định nghĩa lồng nhau, nếu block con không xảy ra lỗi, nó vẫn có thể bị rollback nếu block cha ngoài xảy ra exception. -
Thường atomic block sẽ là block ngoài cùng để đảm bảo mọi thay đổi được commit tới databasse.
-
Sử dụng atomic là decorator function hoặc context manager.
from django.db import transaction
@transaction.atomic
def viewfunc(request):
# This code executes inside a transaction.
do_stuff()
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()
# Try/catch để hanlde integrity error
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()