Integrate
Event Sourcery supports variety of backends and configurations.
Integrating it with your project requires following steps:
- instantiating a corresponding factory class, depending on your storage
- optional configuration, like enabling additional features
- building so-called Backend that exposes features of the library
Event Sourcery defines a few models to keep your events and streams in the database.
When working with SQLAlchemy, you'll typically use alembic to manage your migrations.
Before alembic can detect Event Sourcery models, you need to register them once via configure_models:
from event_sourcery_sqlalchemy import configure_models
configure_models(Base) # Base is your declarative base class
Once our models are registered, migrations generated and executed, you can continue.
You need an instance of Session to instantiate SQLAlchemyBackend:
For async applications, use an AsyncSession with AsyncSQLAlchemyBackend:
from event_sourcery_sqlalchemy.async_ import AsyncSQLAlchemyBackend
session = Session() # SQLAlchemy AsyncSession
backend = AsyncSQLAlchemyBackend().configure(session)
The async variant requires the sqlalchemy-async extra (SQLAlchemy[asyncio]) and an async driver (e.g. asyncpg for PostgreSQL, aiosqlite for SQLite) — drivers are not installed by Event Sourcery, same as in the sync variant.
Note: a single AsyncSession cannot interleave concurrent operations — use one session (and thus one backend) per concurrent unit of work. In-transaction event listeners remain synchronous callables, as they run inside the append transaction.
First, you need an instance of kurrentdbclient.KurrentDBClient that represents a connection to EventStoreDB. Then, you can pass it to KurrentDBBackend:
For async applications, use kurrentdbclient.AsyncKurrentDBClient with AsyncKurrentDBBackend:
import asyncio
from kurrentdbclient import AsyncKurrentDBClient
from event_sourcery import StreamId
from event_sourcery_kurrentdb.async_ import AsyncKurrentDBBackend
async def main() -> None:
client = AsyncKurrentDBClient(uri="kurrentdb://localhost:2113?Tls=false")
backend = AsyncKurrentDBBackend().configure(client)
await backend.event_store.load_stream(StreamId()) # test if connection works
asyncio.run(main())
Note: with the async variant, the outbox persistent subscription is created lazily — before the first append or outbox run — not in with_outbox() (a coroutine cannot be awaited from a sync method).
Your first step will be adding "event_sourcery_django" to the list of INSTALLED_APPS in your settings.
Then you can simply create an instance of DjangoBackend:
This can be done once. Then, you can import backend from other parts of code to use it.
From backend you can grab EventStore instance:
You can now use EventStore to load events from a stream or append new events.