Skip to main content

Event-driven extension for SQLAlchemy that enables listening to database CUD events. This library allows you to react to database changes in real time using a clean, declarative API.

Project description

SQLAlchemy Events

About

Event-driven extension for SQLAlchemy that enables listening to database CUD events. This library allows you to react to database changes in real time using a clean, declarative API.

  • Currently supports PostgreSQL only

Installation

$ pip install sqlalchemy-events-lib

Quick start

Define models with enabled event tracking using @with_events

models.py

import uuid

from sqlalchemy import UUID
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from sqlalchemy_events import with_events, SaEvent


class Base(DeclarativeBase):
    id: Mapped[uuid.UUID] = mapped_column(
        UUID, nullable=False, primary_key=True, default=uuid.uuid4
    )

@with_events([SaEvent.INSERT, SaEvent.UPDATE, SaEvent.DELETE])
class UserModel(Base):
    __tablename__ = 'users'

    name: Mapped[str] = mapped_column()

Define event handlers using decorator @sa_event_handler

services/handlers.py

from models import UserModel
from sqlalchemy_events import sa_event_handler

@sa_event_handler.on_insert(UserModel)
async def handle_user_insert():
    print("User inserted!")

Configure SQLAlchemy async engine

session.py

from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine

from config import DATABASE_URL

engine = create_async_engine(DATABASE_URL)
async_session = async_sessionmaker(engine, expire_on_commit=False, autoflush=False)

Initialize event system and start listening

main.py

import asyncio
from sqlalchemy_events import SQLAlchemyEvents
from models import Base
from session import engine


async def main():
    asyncio.create_task(
        SQLAlchemyEvents(
            base=Base,
            engine=engine,
            autodiscover_paths=['services']
        ).init()
    )
    try:
        await asyncio.sleep(9999)
    except:
        pass

if __name__ == '__main__':
    asyncio.run(main())

Configuration

SQLAlchemyEvents

The SQLAlchemyEvents class accepts the following parameters:

SQLAlchemyEvents(
    base,
    engine,
    autodiscover_paths,
    logger=None
)

Parameters:

  • base - SQLAlchemy declarative base class used to discover mapped models.
  • engine - SQLAlchemy Engine or AsyncEngine instance.
  • autodiscover_paths - List of Python module paths where event handlers are defined. These modules are automatically imported so that decorators such as @sa_event_handler are executed. Example:autodiscover_paths=["services", "app.handlers"]

Important:

All modules containing event handlers must be imported through autodiscover This ensures decorator registration is executed at startup

logger (optional)

A standard Python logging.Logger instance.

If provided, the library will log internal lifecycle events such as:

  • successful initialization
  • listener startup
  • trigger setup

Example:

import logging

logger = logging.getLogger("sqlalchemy_events")
logger.setLevel(logging.INFO)

SQLAlchemyEvents(
    base=Base,
    engine=engine,
    autodiscover_paths=["services"],
    logger=logger
)

How it works

  1. autodiscover_paths modules are imported at startup
  2. Decorators register event handlers into a global registry
  3. Triggers send events via LISTEN/NOTIFY
  4. The library receives notifications and dispatches them to registered handlers

Notes

  • Handlers can be both async and regular functions
  • Only models registered with @with_events will emit events
  • Currently supports LISTEN/NOTIFY
  • Ensure handlers are imported via autodiscover_paths, otherwise they will not be registered

Example flow

INSERT INTO {table} → DATABASE trigger fires → NOTIFY → Python listener receives event → handler is executed

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqlalchemy_events_lib-0.1.1.tar.gz (11.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sqlalchemy_events_lib-0.1.1-py3-none-any.whl (14.3 kB view details)

Uploaded Python 3

File details

Details for the file sqlalchemy_events_lib-0.1.1.tar.gz.

File metadata

  • Download URL: sqlalchemy_events_lib-0.1.1.tar.gz
  • Upload date:
  • Size: 11.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.1 {"installer":{"name":"uv","version":"0.11.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for sqlalchemy_events_lib-0.1.1.tar.gz
Algorithm Hash digest
SHA256 a3f79906f036970c6cc275c27977cc2e1c4edfb04b6c62b374c00941677e4427
MD5 c42e45b2229c4b9289b3cda9fbe0f612
BLAKE2b-256 3a4a91dbc0049ef580f7112f9e23f98ea5a9d3f6282fa04661f7f1f9a7b978e7

See more details on using hashes here.

File details

Details for the file sqlalchemy_events_lib-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: sqlalchemy_events_lib-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 14.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.1 {"installer":{"name":"uv","version":"0.11.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for sqlalchemy_events_lib-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5452dbf1914bf637177f6c8e4cc95841e15247f1cf10c795e1b2b67a204140da
MD5 b7b19fb0b5f4016693854bae2df261f9
BLAKE2b-256 a396f425ccbe5ce1439c743ab22ca9363e87b81ab2122fc971fb31106f16b0d7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page