Connect with Python
Connect a Python application to a Managed PostgreSQL service with the psycopg driver, with TLS certificate verification and credentials read from the environment.
Prerequisites
You need:
- A running Managed PostgreSQL service.
- The Exoscale CLI, configured with your API credentials, and
jq. - Python 3.10 or later, required by the current
psycopg3 releases. - Your client IP address in the service IP filter. See Restrict Connections to a Service.
psycopg uses libpq, so the SSL modes and error messages are the ones described in
Connect with psql. The
service accepts TLS connections only.
Install the driver in a virtual environment. The binary extra ships its own libpq:
python3 -m venv .venv
. .venv/bin/activate
pip install "psycopg[binary]"Retrieve the Credentials and the CA Certificate
eval "$(exo dbaas show SERVICE_NAME -z ZONE -O json | jq -r '.pg.uri_params | "export PGHOST=\(.host) PGPORT=\(.port) PGDATABASE=\(.dbname) PGUSER=\(.user)"')"
export PGPASSWORD="$(exo dbaas user reveal-secrets SERVICE_NAME avnadmin -z ZONE -O json | jq -r .password)"
exo dbaas ca-certificate -z ZONE > ca.pem
export PGSSLROOTCERT="$PWD/ca.pem"Parameters:
SERVICE_NAME: name of your Managed PostgreSQL service, for examplemy-postgresql.ZONE: Exoscale zone the service runs in, for examplech-gva-2.
The JSON output of exo dbaas show does not include the password, which is why the second
command reads it with exo dbaas user reveal-secrets.
Connect
Save the following as main.py:
import os
import psycopg
def connect():
"""Open a TLS-verified connection to Exoscale Managed PostgreSQL."""
return psycopg.connect(
host=os.environ["PGHOST"],
port=os.environ["PGPORT"],
dbname=os.environ["PGDATABASE"],
user=os.environ["PGUSER"],
password=os.environ["PGPASSWORD"],
sslmode="verify-full",
sslrootcert=os.environ["PGSSLROOTCERT"],
connect_timeout=10,
application_name="exoscale-python-sample",
)
def main():
with connect() as conn:
with conn.cursor() as cur:
cur.execute("SELECT version(), current_database(), current_user")
version, database, user = cur.fetchone()
print(f"server: {version}")
print(f"database: {database}")
print(f"user: {user}")
cur.execute(
"SELECT version, cipher FROM pg_stat_ssl WHERE pid = pg_backend_pid()"
)
tls_version, cipher = cur.fetchone()
print(f"tls: {tls_version} {cipher}")
if __name__ == "__main__":
main()Run it:
python main.pyThe last line shows the TLS version and cipher of the session. If PGSSLROOTCERT points to the
wrong certificate, the connection fails with SSL error: certificate verify failed.
Passing the fields as keyword arguments, rather than building a connection string yourself, lets the driver quote and escape the values.
Use a Connection Pool
In a long-running application, reuse connections with psycopg_pool:
pip install "psycopg[binary,pool]"import os
from psycopg.conninfo import make_conninfo
from psycopg_pool import ConnectionPool
conninfo = make_conninfo(
host=os.environ["PGHOST"],
port=os.environ["PGPORT"],
dbname=os.environ["PGDATABASE"],
user=os.environ["PGUSER"],
password=os.environ["PGPASSWORD"],
sslmode="verify-full",
sslrootcert=os.environ["PGSSLROOTCERT"],
)
with ConnectionPool(conninfo, min_size=1, max_size=10) as pool:
with pool.connection() as conn:
print(conn.execute("SELECT now()").fetchone()[0])The with block opens the pool and closes it on exit. Read the server limit with
SHOW max_connections; and keep the sum of max_size across all your application instances
below it, or connect through a server-side pool: see
Manage Connection Pools.
Use psycopg2
With the older psycopg2 driver, the same parameters apply:
import os
import psycopg2
conn = psycopg2.connect(
host=os.environ["PGHOST"],
port=os.environ["PGPORT"],
dbname=os.environ["PGDATABASE"],
user=os.environ["PGUSER"],
password=os.environ["PGPASSWORD"],
sslmode="verify-full",
sslrootcert=os.environ["PGSSLROOTCERT"],
)
try:
with conn.cursor() as cur:
cur.execute("SELECT version()")
print(cur.fetchone()[0])
finally:
conn.close()A psycopg2 connection used as a context manager ends the transaction but does not close the
connection, so close it explicitly.