第一次提交
This commit is contained in:
110
app/utils/transaction.py
Normal file
110
app/utils/transaction.py
Normal file
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
数据库事务管理工具
|
||||
提供统一的事务处理和异常处理机制
|
||||
"""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from flask import current_app
|
||||
from app import db
|
||||
import traceback
|
||||
|
||||
|
||||
class TransactionError(Exception):
|
||||
"""事务错误基类"""
|
||||
pass
|
||||
|
||||
|
||||
class TransactionRollbackError(TransactionError):
|
||||
"""事务回滚错误"""
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def transaction(auto_commit=True, auto_rollback=True):
|
||||
"""
|
||||
事务上下文管理器
|
||||
|
||||
Args:
|
||||
auto_commit: 是否在成功时自动提交
|
||||
auto_rollback: 是否在失败时自动回滚
|
||||
|
||||
Usage:
|
||||
with transaction() as session:
|
||||
# 执行数据库操作
|
||||
pass
|
||||
"""
|
||||
try:
|
||||
yield db.session
|
||||
if auto_commit:
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
if auto_rollback:
|
||||
db.session.rollback()
|
||||
|
||||
# 记录错误日志
|
||||
error_msg = f"事务执行失败: {str(e)}"
|
||||
current_app.logger.error(f"{error_msg}\n{traceback.format_exc()}")
|
||||
|
||||
# 抛出事务错误
|
||||
raise TransactionRollbackError(error_msg) from e
|
||||
|
||||
|
||||
def safe_commit():
|
||||
"""
|
||||
安全提交事务
|
||||
|
||||
Returns:
|
||||
tuple: (success: bool, error: str or None)
|
||||
"""
|
||||
try:
|
||||
db.session.commit()
|
||||
return True, None
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
error_msg = f"事务提交失败: {str(e)}"
|
||||
current_app.logger.error(f"{error_msg}\n{traceback.format_exc()}")
|
||||
return False, error_msg
|
||||
|
||||
|
||||
def safe_rollback():
|
||||
"""
|
||||
安全回滚事务
|
||||
|
||||
Returns:
|
||||
bool: 是否回滚成功
|
||||
"""
|
||||
try:
|
||||
db.session.rollback()
|
||||
return True
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"事务回滚失败: {str(e)}\n{traceback.format_exc()}")
|
||||
return False
|
||||
|
||||
|
||||
def execute_in_transaction(func):
|
||||
"""
|
||||
装饰器:在事务中执行函数
|
||||
|
||||
Args:
|
||||
func: 要执行的函数
|
||||
|
||||
Returns:
|
||||
函数执行结果或TransactionError
|
||||
|
||||
Usage:
|
||||
@execute_in_transaction
|
||||
def create_license():
|
||||
# 创建卡密逻辑
|
||||
pass
|
||||
"""
|
||||
def wrapper(*args, **kwargs):
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
db.session.commit()
|
||||
return result
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
error_msg = f"事务执行失败: {str(e)}"
|
||||
current_app.logger.error(f"{error_msg}\n{traceback.format_exc()}")
|
||||
raise TransactionError(error_msg) from e
|
||||
return wrapper
|
||||
Reference in New Issue
Block a user