Important Notice: ElephantSQL is shutting down. Read all about it in our End of Life Announcement

The recommended way to connect to postgres is via the client psycopg2. Install it with pip install psycopg2. Follow the example to connect with a postgres database. Remember that you need to setup your DATABASE_URL to point either to a local machine or the remote elephantsql instance. Depending on which Python version you are running, choose the appropriate example below.

ElephantSQL with Python3

import os
import urllib.parse as up
import psycopg2

up.uses_netloc.append("postgres")
url = up.urlparse(os.environ["DATABASE_URL"])
conn = psycopg2.connect(database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)

ElephantSQL with Python2

import os
import psycopg2
import urlparse

urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ["DATABASE_URL"])

conn = psycopg2.connect(database=url.path[1:],
  user=url.username,
  password=url.password,
  host=url.hostname,
  port=url.port
)

Python resources