Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Last active February 16, 2021 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariocesar/d405b2860174fe608c88875477c9e9e0 to your computer and use it in GitHub Desktop.
Save mariocesar/d405b2860174fe608c88875477c9e9e0 to your computer and use it in GitHub Desktop.
Psycopg2 utils / PostgreSQL with Python

Create a connection using a database url from Heroku or Digital Ocean App platform

from urllib.parse import urlparse

import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT

def create_connection():
    url = urlparse(os.environ["DATABASE_URL"])
    dbname = url.path[1:]
    user = url.username
    password = url.password
    host = url.hostname
    port = url.port

    conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port)
    conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

    return conn

conn = create_connection()

with conn.cursor() as cursor:
    cursor.execute("select * from pg_user")
    for row in cursor:
        print(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment