Create a TCP connection with SSL certificates by using SQLAlchemy

Create a TCP connection to Cloud SQL for PostgreSQL by using SQLAlchemy with SSL (Secure Sockets Layer) certificates.

Code sample

Python

# Remember - storing secrets in plaintext is potentially unsafe. Consider using
# something like https://cloud.google.com/secret-manager/docs/overview to help keep
# secrets secret.
db_user = os.environ["DB_USER"]
db_pass = os.environ["DB_PASS"]
db_name = os.environ["DB_NAME"]
db_host = os.environ["DB_HOST"]
db_root_cert = os.environ["DB_ROOT_CERT"]
db_cert = os.environ["DB_CERT"]
db_key = os.environ["DB_KEY"]

# Extract port from db_host if present,
# otherwise use DB_PORT environment variable.
host_args = db_host.split(":")
if len(host_args) == 1:
    db_hostname = host_args[0]
    db_port = int(os.environ["DB_PORT"])
elif len(host_args) == 2:
    db_hostname, db_port = host_args[0], int(host_args[1])

ssl_context = ssl.SSLContext()
ssl_context.verify_mode = ssl.CERT_REQUIRED
ssl_context.load_verify_locations(db_root_cert)
ssl_context.load_cert_chain(db_cert, db_key)
ssl_args = {"ssl_context" : ssl_context}

pool = sqlalchemy.create_engine(
    # Equivalent URL:
    # postgresql+pg8000://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name>
    sqlalchemy.engine.url.URL.create(
        drivername="postgresql+pg8000",
        username=db_user,  # e.g. "my-database-user"
        password=db_pass,  # e.g. "my-database-password"
        host=db_hostname,  # e.g. "127.0.0.1"
        port=db_port,  # e.g. 5432
        database=db_name  # e.g. "my-database-name"
    ),
    connect_args=ssl_args,
    **db_config
)

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.