行级锁
必须在事务中使用
select_for_update(nowait=False, skip_locked=False)
entries = models.Entry.objects.select_for_update().filter(author=request.user)
加互斥锁,由于mysql在查询时自动加的是共享锁,所以我们可以手动加上互斥锁。create、update、delete操作时,mysql自动加行级互斥锁,所有匹配的行将被锁定,直到事务结束。
在Web应用中,常用的事务处理方式是将每个请求都包裹在一个事务中。这个功能使用起来非常简单,你只需要将它的配置项ATOMIC_REQUESTS设置为True。
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‘,
......
} #还可以配置其他数据库
}
上面这种方式是统一个http请求对应的所有sql都放在一个事务中执行(要么所有都成功,要么所有都失败)。是全局性的配置, 如果要对某个http请求放水(然后自定义事务),可以用non_atomic_requests修饰器,那么他就不受事务的管控了
from django.db import transaction
@transaction.non_atomic_requests
def my_view(request):
do_stuff()
@transaction.non_atomic_requests(using=‘other‘)
def my_other_view(request):
do_stuff_on_the_other_database()
用法一:
给视图函数加装饰器
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()
do_other_stuff()
原文:https://www.cnblogs.com/journeyer-xsh/p/13716115.html