Helper for handling sqlalchemy events
Use the package manager pip to install sqlalchemy-events.
pip install sqlalchemy-events
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_events import listen_events, on
Base = declarative_base()
@listen_events
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String, nullable=False, unique=True)
@on("before_insert")
def lowercase_username(mapper, conn, self):
self.username = self.username.lower()
List available mapper events is described at sqlalchemy docs