gpt4 book ai didi

python - 在 session 提交时更改对象的属性 - Flask SQLAlchemy

转载 作者:太空狗 更新时间:2023-10-29 21:55:03 31 4
gpt4 key购买 nike

我想在使用 Falsk-SQLAlachemy 将对象插入数据库之前更改对象的属性。我尝试使用 before_models_committed 信号,但它似乎已损坏,所以我尝试改用 models_commited(并重新提交更改),但出现以下错误:

InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.

代码如下:

from app import db
from app import app
from flask.ext.sqlalchemy import models_committed

class Foo(db.Model):
id = db.Column(db.Integer, primary_key=True)
foo_attr = db.Column(db.String(128), index=True)

def on_models_committed(app, changes):
for change in changes:
foo_obj = change[0]
operation = change[1]
if foo_obj.__class__.__name__ == 'Foo':
if operation == 'insert':
foo_obj.foo_attr = get_new_value()
db.session.add(foo_obj)
db.session.commit()
models_committed.connect(on_models_committed)

有没有一种方法可以连接任何信号以在将新对象插入数据库并保存这些更改时执行函数?

谢谢!

最佳答案

好的,我设法使用 SQLAlchemy Mapper Events 做到了。

这段代码:

def on_models_committed(app, changes):
for change in changes:
foo_obj = change[0]
operation = change[1]
if foo_obj.__class__.__name__ == 'Foo':
if operation == 'insert':
foo_obj.foo_attr = get_new_value()
db.session.add(foo_obj)
db.session.commit()
models_committed.connect(on_models_committed)

应替换为以下代码:

def on_foo_created(mapper, connection, foo_obj):
foo_obj.foo_attr = get_new_value()
event.listen(Foo, 'before_insert', on_foo_created)

新的导入语句是:

from flask.ext.sqlalchemy import event

关于python - 在 session 提交时更改对象的属性 - Flask SQLAlchemy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26413668/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com