Django [nine] affairs and lock

First, the transaction

1. Enable global affairs

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.

Copy the code
= {DATABASES 
    'default': { 
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'mxshop', 
        'the HOST': '127.0.0.1', 
        'PORT': '3306', 
        'the USER ':' the root ', 
        ' PASSWORD ':' 123 ', 
        ' the OPTIONS ': { 
            "init_command": "the SET default_storage_engine =' INNODB '", 
       #' init_command ': "the SET the sql_mode =' the STRICT_TRANS_TABLES '", # configure open strictly sql mode 


        } 
        "ATOMIC_REQUESTS": True, # Enable global affairs, is bound to a http request response throughout the process 
        # "aUTOCOMMIT": False, # global cancel automatic submission, caution 
    }, 
  'OTHER ': { 
    ' ENGINE ':' django.db.backends.mysql ', 
            ...... 
  } # can also configure other databases 
}
Copy the code

2, topical affairs

Atomicity is a property database transaction. Use atomic, we can create a block of code includes atomic. Upon completion of block normal operation, all the modifications are committed to the database. Conversely, if there is an exception, the changes will be rolled back.

Manage the atomic block may also code embedded to the method. In this case, even if the internal code block normal operation, if external code block throws an exception, then it is no way to submit its changes to the database.

Usage 1: function to do the decorators to use

from django.db import transaction

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

Usage 2: used as a context manager, in fact, saved set points affairs

Copy the code
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()

    do_other_stuff()
Copy the code

Second, lock

select_for_update () 
the SELECT * from T1 for Update 
models.T1.objects.select_for_update (). filter (the above mentioned id = 1) # exclusive lock (mutex) not read nor write

Three, MySQL in locking and transactions

MySQL default auto commit,
verify lock, first commit automatically canceled;

Transaction:

Open a business, we must manually commit, the transaction will end:

Guess you like

Origin www.cnblogs.com/youxiu123/p/11600536.html