psycogreen

1.0.2 · maintenance · verified Sun Apr 12

Psycogreen is a library that enables the `psycopg2` PostgreSQL adapter to work with coroutine-based libraries like Gevent and Eventlet. It provides "wait callbacks" that integrate `psycopg2`'s asynchronous calls with the event loops of these coroutine libraries, allowing `psycopg2` to operate in a non-blocking manner within a green-thread environment while presenting a synchronous interface to the application. The library is currently at version 1.0.2, with no new releases since 2020, suggesting it is in maintenance mode.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates patching `psycopg2` with `psycogreen` for use with Gevent. It's crucial to call `gevent.monkey.patch_all()` and `psycogreen.gevent.patch_psycopg()` early in your application's lifecycle, typically before any `psycopg2` imports or connections are made. The example connects to a PostgreSQL database using environment variables for credentials and executes a simple query.

import os
import gevent.monkey
import psycopg2

# Apply gevent monkey patching for standard library modules
gevent.monkey.patch_all()

# Apply psycogreen patching for psycopg2
from psycogreen.gevent import patch_psycopg
patch_psycopg()

# Now psycopg2 operations will yield to gevent
try:
    # Use os.environ.get for database connection details for runnable example
    conn = psycopg2.connect(
        host=os.environ.get('PGHOST', 'localhost'),
        database=os.environ.get('PGDATABASE', 'testdb'),
        user=os.environ.get('PGUSER', 'postgres'),
        password=os.environ.get('PGPASSWORD', 'password'),
        port=os.environ.get('PGPORT', '5432')
    )
    cur = conn.cursor()
    cur.execute("SELECT 1 + 1 AS result;")
    result = cur.fetchone()[0]
    print(f"PostgreSQL query result (green): {result}")
    cur.close()
    conn.close()
except psycopg2.OperationalError as e:
    print(f"Could not connect to PostgreSQL. Please ensure a PostgreSQL instance is running and accessible. Error: {e}")
except ImportError as e:
    print(f"Required modules (gevent, psycogreen, psycopg2) not installed. Error: {e}")

view raw JSON →