python 相关框架事务开启方式

前言

对于框架而言,各式API接口少不了伴随着事务的场景,下面就列举常用框架的事务开启方法

一、Django

python 复制代码
import traceback
from django.db import transaction
from django.contrib.auth.models import User
try:
	with transaction.atomic():  # 在with语句体中,要成功都成功,要失败都失败
		# User.objects.filter(id=66).update(username="test_username")
		transaction1
		transaction2
		transaction3
		.
		.
		.
		# b = 1 / 0
except Exception as e:
	print(traceback.format_exc())

二、flask-sqlalchemy

注:利用begin_nested方法,会开启一个子事务!实现数据库变更需将子事务提交再将主事务提交才行

2.1、样例模板

python 复制代码
db.session.begin_nested()
# obj = Mytable.query.filter_by(id=68).first()
# obj.desc = "test-demo"
transaction1
transaction2
transaction3
.
.
.
# 子事务提交
db.session.commit()
# b = 1 / 0
# 主事务提交
db.session.commit()

2.2、进化版

python 复制代码
with db.session.begin_nested():  # 在with语句体(自带子事务提交)中,要成功都成功,要失败都失败
	# obj = Mytable.query.filter_by(id=88).first()
	# obj.desc = "test-demo"
	transaction1
	transaction2
	transaction3
	.
	.
	.
    # b = 1 / 0
db.session.commit()

结束!

相关推荐
麦兜*12 分钟前
MongoDB 6.0 新特性解读:时间序列集合与加密查询
数据库·spring boot·mongodb·spring·spring cloud·系统架构
chat2tomorrow15 分钟前
数据采集平台的起源与演进:从ETL到数据复制
大数据·数据库·数据仓库·mysql·低代码·postgresql·etl
2401_8288906416 分钟前
使用 BERT 实现意图理解和实体识别
人工智能·python·自然语言处理·bert·transformer
稻草人想看远方18 分钟前
关系型数据库和非关系型数据库
数据库
考虑考虑19 分钟前
Postgerssql格式化时间
数据库·后端·postgresql
千里码aicood27 分钟前
【springboot+vue】党员党建活动管理平台(源码+文档+调试+基础修改+答疑)
java·数据库·spring boot
TDengine (老段)1 小时前
TDengine 选择函数 Max() 用户手册
大数据·数据库·物联网·时序数据库·tdengine·涛思数据
驾驭人生1 小时前
Asp .Net Core 系列:Asp .Net Core 集成 Hangfire+MySQL
数据库·mysql·.netcore
xhbh6661 小时前
不止是DELETE:MySQL多表关联删除的JOIN语法实战详解
数据库·mysql·程序员·mysql删除语句
多恩Stone1 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc