gpt4 book ai didi

python - 作用域 session 上的事件监听器

转载 作者:太空狗 更新时间:2023-10-30 00:07:17 24 4
gpt4 key购买 nike

我正在尝试将事件监听器添加到 Flask 应用程序内 SQLAlchemy session 的 before_commit 事件。在进行以下操作时

def before_commit(session):
for item in session:
if hasattr(item, 'on_save'):
item.on_save(session)

event.listen(db.session, 'before_commit', before_commit)

我明白了

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "app.py", line 60, in <module>
event.listen(db.session, 'before_commit', before_commit)
File "C:\Python27\lib\site-packages\sqlalchemy\event\api.py", line 49, in listen
_event_key(target, identifier, fn).listen(*args, **kw)
File "C:\Python27\lib\site-packages\sqlalchemy\event\api.py", line 22, in _event_key
tgt = evt_cls._accept_with(target)
File "C:\Python27\lib\site-packages\sqlalchemy\orm\events.py", line 1142, in _accept_with
"Session event listen on a scoped_session "
sqlalchemy.exc.ArgumentError: Session event listen on a scoped_session requires that its creation callable is associated with the Session class.

我找不到注册事件监听器的正确方法。文档实际上指出 event.listen() 也接受 scoped_session,但它似乎不接受?!


http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.SessionEvents

The listen() function will accept Session objects as well as the return result of sessionmaker() and scoped_session().

Additionally, it accepts the Session class which will apply listeners to all Session instances globally.

最佳答案

这意味着你传递给 scoped_session() 的工厂必须是一个 sessionmaker():

from sqlalchemy.orm import scoped_session, sessionmaker, sessionmaker
from sqlalchemy import event

# good

ss1 = scoped_session(sessionmaker())

@event.listens_for(ss1, "before_flush")
def evt(*arg, **kw):
pass

# bad

ss2 = scoped_session(lambda: Session)

@event.listens_for(ss2, "before_flush")
def evt(*arg, **kw):
pass

关于python - 作用域 session 上的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21322158/

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