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

结束!

相关推荐
smj2302_796826527 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
笨蛋不要掉眼泪7 小时前
MySQL架构揭秘:慢查询日志详解
数据库·mysql·架构
pulinzt7 小时前
Tableau的基础使用
数据库·numpy
糖果店的幽灵7 小时前
【langgraph 从入门到精通graphApi 篇】LangGraphAPI 方式调用 - 初识与核心概念
数据库·人工智能·langgraph
吴梓穆8 小时前
Python 基础 正则表达式
python
巧克力男孩dd8 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
TlSfoward8 小时前
TLSFOWARD TLS指纹
开发语言·数据库·爬虫·搜索引擎·https·php
️学习的小王8 小时前
MySQL 实战:从建表到索引管理的完整指南
数据库·mysql·oracle
闲猫9 小时前
LangChain / Core components / Models
开发语言·python·langchain
宠友信息10 小时前
MySQL复合索引与Druid优化仿小红书源码个人主页查询链路
数据库·spring boot·websocket·mysql·uni-app