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

结束!

相关推荐
知识分享小能手2 小时前
Redis入门学习教程,从入门到精通,Redis 概述:知识点详解(1)
数据库·redis·学习
xixihaha13243 小时前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
夕除4 小时前
Mysql--07
数据库·mysql
数据最前线4 小时前
5个瞬间,盘点国产数据库的2025年
数据库
jiankeljx4 小时前
Redis-配置文件
数据库·redis·oracle
xixihaha13244 小时前
Python游戏中的碰撞检测实现
jvm·数据库·python
Schengshuo4 小时前
SQL 中 COUNT 的用法详解
数据库·sql
顶点多余4 小时前
Mysql--后端与前端关系
数据库·mysql
mygljx4 小时前
【MySQL 的 ONLY_FULL_GROUP_BY 模式】
android·数据库·mysql
sunwenjian8864 小时前
Springboot项目本地连接并操作MySQL数据库
数据库·spring boot·mysql