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()

结束!

相关推荐
郝学胜-神的一滴15 小时前
FastAPI:Python 高性能 Web 框架的优雅之选
开发语言·前端·数据结构·python·算法·fastapi
数据知道15 小时前
MongoDB 数组查询专项:`$all`、`$elemMatch` 与精确匹配数组的使用场景
数据库·mongodb
柒.梧.16 小时前
Java位运算详解:原理、用法及实战场景(面试重点)
开发语言·数据库·python
callJJ16 小时前
深入浅出 MVCC —— 从零理解 MySQL 并发控制
数据库·mysql·面试·并发·mvcc
Scott.W16 小时前
跟我学Easyi3C Tower Adapter Console(9)
人工智能·python·嵌入式硬件·i3c
多恩Stone16 小时前
【3D-AICG 系列-14】Trellis 2 的 Texturing Pipeline 保留单层薄壳,而 Textured GLB 会变成双层
人工智能·python·算法·3d·aigc
小杜的生信筆記16 小时前
生信技能技巧小知识,Linux多线程压缩/解压工具
linux·数据库·redis
刘恒12345678916 小时前
Windows 电脑文件夹手动分类指南
java·windows·python·电脑·php
测试渣16 小时前
持续集成中的自动化测试框架优化实战指南
python·ci/cd·单元测试·自动化·pytest
Smoothcloud润云16 小时前
Google DeepMind 学习系列笔记(3):Design And Train Neural Networks
数据库·人工智能·笔记·深度学习·学习·数据分析·googlecloud