ORM in the lock and transactions

lock

Locking sql statement

select * from book where id=1 for update;
begin;  
start transaction;
select * from t1 where id=1 for update;
commit

rollback;

django orm

models.Book.objects.select_for_update().filter(id=1)

Global Transactions

    In the Web application, is commonly used in transaction processing mode are wrapped each request in a transaction. This feature is very simple to use, you only need to configure its entry ATOMIC_REQUESTS set to True.

    It works like this: When the request came, Django will open a transaction before calling the view method. If the request was properly prepared and correctly returns the result, Django will commit the transaction. Otherwise, Django will roll back the transaction.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mxshop',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123',
        'OPTIONS': {
            "init_command": "SET default_storage_engine='INNODB'",
       #'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", #配置开启严格sql模式


        }
        "ATOMIC_REQUESTS": True, #全局开启事务,绑定的是http请求响应整个过程
        "AUTOCOMMIT":False, #全局取消自动提交,慎用
    },
  'other':{
    'ENGINE': 'django.db.backends.mysql', 
            ......
  } #还可以配置其他数据库
}

Local Services

Usage 1

View all orm are added Affairs

from django.db import transaction

@transaction.atomic
def viewfunc(request):
    pass              #此视图中所有的orm都加上了事务

Usage 2:

Used as a context manager, in fact, saved set points affairs

A partial view of use

from django.db import transaction

def viewfunc(request):

    do_stuff()

    with transaction.atomic():   #保存点
        
        do_more_stuff()

    do_other_stuff()

Usage 3: may also be nested, nested transaction context manager function of the transaction, the transaction context manager nested transaction context manager and the like. The following are examples of nested functions context:

from django.db import IntegrityError, transaction

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

    try:
        with transaction.atomic():
            generate_relationships()
       #other_task()  #还要注意一点,如果你在事务里面写了别的操作,只有这些操作全部完成之后,事务才会commit,也就是说,如果你这个任务是查询上面更改的数据表里面的数据,那么看到的还是事务提交之前的数据。
    except IntegrityError:
        handle_exception()

    add_children()

Guess you like

Origin www.cnblogs.com/zdqc/p/11756117.html