Aiopg

1.4.0 · active · verified Mon Apr 13

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.

Warnings

Install

Imports

Quickstart

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.

import asyncio
import aiopg
import os

dsn = os.environ.get('AIOPG_DSN', 'dbname=aiopg user=aiopg password=passwd host=127.0.0.1')

async def main():
    # Establish a connection pool
    async with aiopg.create_pool(dsn) as pool:
        # Acquire a connection from the pool
        async with pool.acquire() as conn:
            # Open a cursor to perform database operations
            async with conn.cursor() as cur:
                # Execute a simple query
                await cur.execute("SELECT 1")
                ret = []
                # Iterate over the results
                async for row in cur:
                    ret.append(row)
                assert ret == [(1,)]
                print(f"Query result: {ret}")

if __name__ == '__main__':
    # For Python 3.10+
    try:
        asyncio.run(main())
    except RuntimeError as e:
        if "cannot run an event loop while another loop is running" in str(e):
            # Handle cases where an event loop might already be running (e.g., in notebooks)
            loop = asyncio.get_event_loop()
            if loop.is_running():
                loop.create_task(main())
            else:
                loop.run_until_complete(main())
        else:
            raise

view raw JSON →