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

结束!

相关推荐
卷无止境1 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
ltl1 小时前
数据库作为 LLM 记忆体:语义缓存、RAG 与一致性
数据库
ltl1 小时前
WAL 与崩溃恢复:ARIES 协议怎么跑通
数据库
ltl1 小时前
TEE 数据库:EnclaveDB、Oblivious 原语与机密 SQL
数据库
zhanghaha13141 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教2 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教2 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境2 小时前
FastAPI 的Admin面板生态
后端·python
麻瓜code3 小时前
【Mysql】重新学一遍 SQL 执行顺序
数据库·sql
ctlover3 小时前
Streamlit 框架
python