asyncpg-client
is a powerful Python package designed for seamless asynchronous interactions with PostgreSQL, leveraging SQLAlchemy. It ensures efficient, thread-safe operations with its singleton-based connection pooling mechanism, making database management easier and faster.
Source Code | Website |
---|---|
github.com/deepmancer/asyncpg-client | deepmancer.github.io/asyncpg-client |
- ⚡ Asynchronous Operations: Asynchronous database connections using SQLAlchemy for high performance.
- 🛠️ Singleton Pattern: Efficiently manage database connections using a singleton design.
- 🔄 Context Manager Support: Simplify database session management with context managers.
- 🔧 Easy Configuration: Configure your database effortlessly with
PostgresConfig
.
Get started quickly by installing asyncpg-client
with pip:
pip install git+https://github.com/deepmancer/asyncpg-client.git
Start by creating a configuration object with PostgresConfig
:
from asyncpg_client import PostgresConfig
config = PostgresConfig(
host='localhost',
port=5432,
user='your_user',
password='your_password',
database='your_database',
url=None, # Optional: Direct database URL
enable_db_echo_log=False,
enable_db_expire_on_commit=False
)
Next, create an instance of AsyncPostgres
using your configuration:
from asyncpg_client import AsyncPostgres
async def main():
pg_client = await AsyncPostgres.create(config=config)
print(pg_client.async_url)
print(pg_client.sync_url)
Interact with your PostgreSQL database using the context manager from get_or_create_session
:
from asyncpg_client import AsyncPostgres
async def main():
pg_client = await AsyncPostgres.create(config=config)
async with pg_client.get_or_create_session() as session:
# Interact with your database here
pass
await pg_client.disconnect()
Here's a basic example to demonstrate how asyncpg-client
works:
import asyncio
from asyncpg_client import AsyncPostgres, PostgresConfig
async def main():
config = PostgresConfig(
host='localhost',
port=5432,
user='your_user',
password='your_password',
database='your_database'
)
pg_client = await AsyncPostgres.create(config=config)
async with pg_client.get_or_create_session() as session:
# Perform your database operations here
pass
await pg_client.disconnect()
if __name__ == "__main__":
asyncio.run(main())
Handle various database-related errors gracefully with custom exceptions:
PGConnectionError
PGSessionCreationError
PGEngineInitializationError
Ensure a clean disconnect from your PostgreSQL database:
await pg_client.disconnect()
This project is licensed under the Apache License 2.0. See the LICENSE file for full details.