Postgres.py - A PostgreSQL Client Abstraction

4.0 · active · verified Thu Apr 16

postgres is a high-value abstraction over the psycopg2 database driver, simplifying interactions with PostgreSQL databases. Currently at version 4.0, the library offers a more Pythonic API, an Object-Relational Mapper (ORM), and improved cursor management. Releases are made as needed, focusing on usability and PostgreSQL-specific features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a PostgreSQL database using `postgres.py`, create a table, insert data, and fetch results using `run()`, `one()`, and `all()` methods. It also illustrates the use of bind parameters for safe query execution.

import os
from postgres import Postgres

# Ensure PostgreSQL is running and accessible, e.g., on localhost:5432
# and 'test_db' exists with user 'postgres' and no password (or configure as needed).
# For production, use environment variables or a configuration management system.

db_url = os.environ.get('POSTGRES_URL', 'postgres://postgres:@localhost:5432/test_db')

try:
    db = Postgres(db_url)
    
    # Run SQL statements
    db.run("DROP TABLE IF EXISTS foo")
    db.run("CREATE TABLE foo (bar TEXT, baz INT)")
    db.run("INSERT INTO foo (bar, baz) VALUES ('buz', 42)")
    db.run("INSERT INTO foo (bar, baz) VALUES ('bit', 537)")
    print("Table 'foo' created and data inserted.")

    # Fetch a single result or None
    result_one = db.one("SELECT * FROM foo WHERE bar='buz'")
    print(f"Single result for 'buz': {result_one}")

    # Fetch all results
    results_all = db.all("SELECT * FROM foo ORDER BY bar")
    print(f"All results, ordered: {results_all}")
    
    # Using bind parameters to prevent SQL injection
    param_value = 'buz'
    result_param = db.one("SELECT baz FROM foo WHERE bar=%(value)s", value=param_value)
    print(f"Result using bind parameter for 'buz' baz: {result_param}")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure your PostgreSQL server is running and the connection details are correct.")

view raw JSON →