flask-sqlalchemy 默认是开始事务的,那么如何标记一组操作为一个 transaction 要么全成功要么全失败?
以下代码片段,提供的参数要求具有唯一性,所以最后一条肯定插入失败,但是前两条却成功了。
想要的效果是,把这三个插入最为一个事务呢,要么全成功要么全失败
完整代码如下
from flask import Flask from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Integer, String, Column
db = SQLAlchemy()
# 模型
class User(db.Model):
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(10), nullable=False, unique=True)
def __init__(self, username):
self.username = username
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+cymysql://root:12345678@localhost/test_sqlalchemy'
db.init_app(app)
with app.app_context():
db.create_all()
return app
app = create_app()
@app.route("/hello")
def hello_world():
users = [User("111"), User("222"), User("111")]
try:
db.session.add_all(users)
db.session.commit()
except:
db.session.rollback()
return "hello_wold"
if __name__ == "__main__":
app.run(debug\=True)
回答:
如果你只是想多条语句全部成功才入库,可以如此这般,然后外部捕获错误
db.session.add_all([ User("111", 1),
User("111", 3),
User("222", 2),
])
db.session.commit()
flask-sql 对SQLAlchemy进行了抽象,将它的api进行了简化。所以若想用事务块,还是得找他大爷sqlalchemy,换句话来说要用Transaction
对象
connection = engine.connect()trans = connection.begin()
try:
r1 = connection.execute(table1.select())
connection.execute(table1.insert(), col1=7, col2='this is some data')
trans.commit()
except:
trans.rollback()
raise
回答:
我本地试了下,并没有啥问题:
\# todo: test try:
db.session.add(User("111", 1))
db.session.add(User("222", 2))
db.session.add(User("111", 3))
db.session.commit()
except Exception as e:
db.session.rollback()
raise e
以上是 flask-sqlalchemy 默认是开始事务的,那么如何标记一组操作为一个 transaction 要么全成功要么全失败? 的全部内容, 来源链接: utcz.com/p/937713.html