Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy events are not working

I'm working with SQLAlchemy and tried to add events to my code. While everything works, the events are not being triggered. Here is my simplified code:

from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import event

alchemy_base = declarative_base()

class Person(alchemy_base):
    __tablename__ = 'my_table'
    name = Column(String, primary_key=True)

@event.listens_for(Person, "before_insert")
def before_insert(mapper, connection, instance):
    print("before_insert", mapper, connection, instance)

engine = create_engine('sqlite:///:memory:', echo=True)
alchemy_base.metadata.create_all(engine)
session_maker = sessionmaker(bind=engine)
session = session_maker()

insert_dicts = [{'name': "ami"}, {'name': "beni"}]
engine.execute(Person.__table__.insert(), insert_dicts)
session.commit()

The function before_insert is not being called, although the values are entered into the DB.

I'm using python 2.7.10 on Mac OS, SQLAlchemy 1.0.10.

like image 580
Periodic Maintenance Avatar asked Jan 13 '16 18:01

Periodic Maintenance


1 Answers

before_insert is an ORM event. You are using the SQLAlchemy Core instead of the ORM. This works.

>>> p = Person(name='Ami')
>>> session.add(p)
>>> session.commit()
2016-01-13 23:37:42,887 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
('before_insert', <Mapper at 0x1059e4dd0; Person>, <sqlalchemy.engine.base.Connection object at 0x105a2e990>, <__main__.Person object at 0x105a2e790>)
2016-01-13 23:37:42,888 INFO sqlalchemy.engine.base.Engine INSERT INTO my_table (name) VALUES (?)
2016-01-13 23:37:42,888 INFO sqlalchemy.engine.base.Engine ('Ami',)
2016-01-13 23:37:42,888 INFO sqlalchemy.engine.base.Engine COMMIT
like image 182
jumbopap Avatar answered Nov 15 '22 02:11

jumbopap