An open API service indexing awesome lists of open source software.

https://github.com/olirice/realtime

Realtime Subscription to PostgreSQL for Python
https://github.com/olirice/realtime

postgresql python sqlalchemy

Last synced: about 2 months ago
JSON representation

Realtime Subscription to PostgreSQL for Python

Awesome Lists containing this project

README

          

# Realtime

Tests
Tests


Codestyle Black


Python version
PyPI version
License
Download count

---

**Documentation**: https://realtime.readthedocs.io/en/latest/

**Source Code**: https://github.com/olirice/realtime

---

Realtime enables listening for changes in a PostgreSQL Database

This package is under active development and may change significantly. There is no stability guarentee. If you see something you like, please vendor it, or use at your own risk.

Thanks,

Oli

## Setup

Realtime relies on postgres using logical replication. Set it up using:

```sql
-- Ensure WAL replication is set to 'logical'
ALTER SYSTEM SET wal_level = logical;

-- Allow a few replication slots
ALTER SYSTEM SET max_replication_slots = 5; -- any value > 0

/*
-- Create a publication
Spec:
CREATE PUBLICATION name
[ FOR TABLE [ ONLY ] table_name [ * ] [, ...]
| FOR ALL TABLES ]
[ WITH ( publication_parameter [= value] [, ... ] ) ]
*/
CREATE PUBLICATION realtime_py FOR ALL TABLES;
```

Then, restart your postgres instance.

#### Notes

##### Docker
If you're using docker, you can restart the postgres instance after issuing the commands above via
```
docker restart
```

##### AWS - RDS
AWS RDS does not grant superuser access to postgres instances. That level of access is required to issue `ALTER SYSTEM` commands. To enable logical replication on RDS, the value for `wal_level` can be set by creating a new parameter group and assigning it to the RDS instance.

A reboot will still be required. That can also be done from the RDS UI.
```
RDS > Databases > > Configuration > Parameter group
```

## Usage

```python
from realtime.subscribe import subscribe
from sqlalchemy.ext.asyncio import create_async_engine

connection_string = "postgresql+asyncpg://:@:/"

engine = create_async_engine(connection_string)

async with engine.connect() as conn:

subscription = subscribe(con=conn, slot_name="realtime_example")

async for message in subscription:
# Business Logic Goes Here
print(message)
```

where example outputs are:

```python
from realtime.message import TransactionMessage, CRUDMessage, Column

TransactionMessage(command="COMMIT", lsn=95)
# OR
CRUDMessage(
command="INSERT",
schema="public",
table="account",
columns=[
Column(column="id", data_type="integer", value=5),
Column(column="email", data_type="text", value="example@example.com"),
]
)
```