aiopg is a library for accessing a PostgreSQL database from the asyncio (PEP-3156/tulip) framework. It wraps asynchronous features of the Psycopg database driver. The current version is 1.4.0, and it is actively maintained by the aio-libs organization, though the last release was in October 2022.
pip install aiopgVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to establish an asynchronous connection pool, acquire a connection, execute a simple query, and fetch results using aiopg. It includes error handling for already running event loops common in interactive environments. Ensure your PostgreSQL instance is running and accessible with the provided DSN, or set the AIOPG_DSN environment variable.
Do not call `conn.commit()` or `conn.rollback()`. Instead, explicitly execute SQL: `await cur.execute('BEGIN')`, then `await cur.execute('COMMIT')` or `await cur.execute('ROLLBACK')`.Ensure all `aiopg` connection and cursor methods are `await`ed, e.g., `await conn.execute(...)`, `await cur.fetchone()`. For `cur.mogrify()`, do not use `await`.
Prefer explicit iteration using `async for row in cur:` for cursors, and `await result.fetchall()` or `async for row in result:` for `ResultProxy` objects, rather than synchronous iteration.
Ensure your project uses Python 3.7 or newer and exclusively uses `async def` and `await` for asynchronous code.
Avoid passing `name`, `scrollable`, or `withhold` to `conn.cursor()`. If custom cursor behavior is needed, use `cursor_factory`.
Upgrade to aiopg version 0.12 or later, which includes support for Windows by handling the absence of the 'fcntl' module.
Set the event loop policy to WindowsSelectorEventLoopPolicy by adding 'asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())' before running your asyncio code.
Use the synchronous psycopg2 library for operations requiring 'copy_from', or find an alternative method compatible with asynchronous execution.
Install the library using pip: `pip install aiopg`.
Ensure `aiopg.Pool` is initialized with the correct parameters, usually `dsn`, `minsize`, `maxsize`, and `timeout`. For example: `await aiopg.create_pool(dsn='dbname=test', minsize=1, maxsize=10, timeout=30)`.