Python 3.x SQLAlchemy@event.listens#u(类,在插入';之后)为SQL表达式";在表格(cols)中插入值;

Python 3.x SQLAlchemy@event.listens#u(类,在插入';之后)为SQL表达式";在表格(cols)中插入值;,python-3.x,postgresql,sqlalchemy,Python 3.x,Postgresql,Sqlalchemy,在我的应用程序中,数据将从不同的系统(使用scoop从hive)流向postgres数据库。我想在将代码插入到其中一个表时自动运行一些代码(我使用sqlaLchemy ORM创建了它-我知道在插入钩子之后,它对sqlaLchemy Core不起作用)。就我而言,我不能使用postgres触发器 这是我的数据模型: from sqlalchemy.orm import declarative_base, Session from sqlalchemy import Column, Integer,

在我的应用程序中,数据将从不同的系统(使用scoop从hive)流向postgres数据库。我想在将代码插入到其中一个表时自动运行一些代码(我使用sqlaLchemy ORM创建了它-我知道在插入钩子之后,它对sqlaLchemy Core不起作用)。就我而言,我不能使用postgres触发器

这是我的数据模型:

from sqlalchemy.orm import declarative_base, Session
from sqlalchemy import Column, Integer, String, event, DDL

Base = declarative_base()

class MainClass(Base):
    __tablename__ = 'first_table'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

@event.listens_for(MainClass, 'after_insert')
def after_insert(Mapper, connection, target):
    connection.execute(DDL(f'''INSERT INTO second_table(name, value) VALUES ('OK!', '{target.name}')'''))


class SecondClass(Base):
    __tablename__ = 'second_table'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    value = Column(String, nullable=False)

Base.metadata.create_all(engine, checkfirst=True)
什么不起作用:

engine.execute('''INSERT INTO first_table(name) VALUES ('test1')''')
什么是有效的(但我不能在我的案例中使用这种插入):

说:

方法sqlalchemy.orm.MapperEvents.after\u插入(映射器、连接、目标)

在发出与该实例对应的INSERT语句后接收该对象实例

示例参数形式:

此事件用于在插入发生后修改实例的纯Python状态,以及在给定连接上发出其他SQL语句

在上一步中一次发出同一类的一批对象的INSERT语句后,通常会为这些对象调用该事件。在极少数情况下,这是不可取的,映射器()可以配置为batch=False,这将导致实例的批被分解为单独的(且性能更差的)事件->持久->事件步骤


如果这是sqlAlchemy ORM事件不支持的内容。您能给我推荐一些解决方法吗?

您正在通过执行原始SQL绕过ORM,因此ORM事件侦听器无法工作。如果您需要执行原始SQL,您可能可以对表执行一些操作或向表中添加触发器
insert = MainClass(name='test2')

with Session(bind=engine) as session:
    session.add(insert)
    session.commit()
from sqlalchemy import event
    @event.listens_for(SomeClass, 'after_insert')
    def receive_after_insert(mapper, connection, target):
        "listen for the 'after_insert' event"