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 decorators @sa_insert_handler, @sa_update_handler, @sa_delete_handler

services/handlers.py

from models import UserModel
from sqlalchemy_events import sa_insert_handler

@sa_insert_handler(UserModel)
async def handle_user_insert():
    print('User inserted!')

Optional Argument: rows Handlers can optionally accept a rows argument.

If the parameter is declared in the function signature, it will automatically receive a list of affected row IDs.

from models import UserModel
from sqlalchemy_events import sa_insert_handler

@sa_insert_handler(UserModel)
async def handle_user_insert(rows: list[DB_ID]):
    print('Users inserted!', rows)

Output:

Users inserted! ['3310aa38-f555-4c05-a57f-5acae32a0a7b', '6aeba1b0-8e80-4369-8adf-cf967ab7ba7a']

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 session import engine


async def main():
    sa_events = SQLAlchemyEvents(
        engine=engine,
        autodiscover_paths=['services']
    )
    await sa_events()
    while True:
        await asyncio.sleep(9999)

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

Configuration

SQLAlchemyEvents

The SQLAlchemyEvents class accepts the following parameters:

SQLAlchemyEvents(
    engine,
    autodiscover_paths,
    logger=None,
    verbose=True
)

Parameters:

  • 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_insert_handler, @sa_update_handler, @sa_delete_handler are executed.
    Example:
    autodiscover_paths=["services", "app.handlers"]

  • verbose - Enables detailed logging output. When set to True, the library will log additional informational and warning messages to help with debugging and configuration.

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
import asyncio
from sqlalchemy_events import SQLAlchemyEvents
from session import engine

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

async def main():
    sa_events = SQLAlchemyEvents(
        engine=engine,
        autodiscover_paths=['services'],
        logger=logger
    )
    await sa_events()
    while True:
        await asyncio.sleep(9999)

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

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/UPDATE/DELETE FROM {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.3.2.tar.gz (15.2 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.3.2-py3-none-any.whl (18.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: sqlalchemy_events_lib-0.3.2.tar.gz
  • Upload date:
  • Size: 15.2 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.3.2.tar.gz
Algorithm Hash digest
SHA256 24b946dffc4338ab9a47744bf064a95f9a62c1a13c403e4903718d93a8a03f47
MD5 68ef10097027143b7cf2893f66d08872
BLAKE2b-256 451e7c15462b37b1bd599acb2ad76464ed0d117da4a886ddc0b5e93531b0ee17

See more details on using hashes here.

File details

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

File metadata

  • Download URL: sqlalchemy_events_lib-0.3.2-py3-none-any.whl
  • Upload date:
  • Size: 18.8 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.3.2-py3-none-any.whl
Algorithm Hash digest
SHA256 7cf8749457cbecd4a26cd5636da29bc9af15b08f6c1e7aeddd1f6490403ac79d
MD5 760597b507f020dde82a1167273364b8
BLAKE2b-256 bd2ed2c5e59bfa4065acdb59d0e91493b68f343dbd3b612842e9affeb8f7470e

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