MagicStack / asyncpg

A fast PostgreSQL Database Client Library for Python/asyncio.
Apache License 2.0
6.88k stars 399 forks source link

[HELP] PostgreSQL cluster: how to setup more than one host #1072

Closed tyki6 closed 11 months ago

tyki6 commented 1 year ago

Hello, I request some helm from your side guys. I created a postgres cluster on aws with one master and one read replica. My expected goal with asynpg is via url said to asyncpg both host one for write one for read how is it possible? Regards,

Example

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
postgres_url = "postgresql+asyncpg:master_user:master_password@master_host:5432/mydatabase,replica_user:replica_password@replica_host1:5432/mydatabase
engine_async = create_async_engine(, pool_size=200, max_overflow=10, echo=False)
session_local_async = async_sessionmaker(engine_async, class_=AsyncSession, autoflush=False, expire_on_commit=False)

async def get_db_async() -> AsyncGenerator[AsyncSession, None]:
    async with session_local_async() as session:
        try:
            yield session
        finally:
            await session.close()
elprans commented 1 year ago

The correct DSN would be this (see docs)

postgres_url = "postgresql+asyncpg:master_user:master_password@master_host,replica_host:5432/mydatabase"

You can control whether you need a read-write or read-only connection via the target_session_attrs argument to connect().