Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions python/sqlalchemy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,19 @@ The code automatically detects the user type and adjusts its behavior accordingl
* This code is not tested in every AWS Region. For more information, see
[AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).

## TLS connection configuration

This example uses direct TLS connections where supported, and verifies the server certificate is trusted. Verified SSL
connections should be used where possible to ensure data security during transmission.

* Driver versions following the release of PostgreSQL 17 support direct TLS connections, bypassing the traditional
PostgreSQL connection preamble
* Direct TLS connections provide improved connection performance and enhanced security
* Not all PostgreSQL drivers support direct TLS connections yet, or only in recent versions following PostgreSQL 17
* Ensure your installed driver version supports direct TLS negotiation, or use a version that is at least as recent as
the one used in this sample
* If your driver doesn't support direct TLS connections, you may need to use the traditional preamble connection instead

## Run the example

### Prerequisites
Expand Down
19 changes: 13 additions & 6 deletions python/sqlalchemy/src/example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## Dependencies for engine creation
import os
import psycopg2.extensions
from sqlalchemy import create_engine, select, event
from sqlalchemy.engine import URL

Expand Down Expand Up @@ -42,13 +43,19 @@ def create_dsql_engine():
host=cluster_endpoint,
database="postgres"
)


connect_args = {
"sslmode": "verify-full",
"sslrootcert": "./root.pem",
}

# Use the more efficient connection method if it's supported.
if psycopg2.extensions.libpq_version() >= 170000:
connect_args["sslnegotiation"] = "direct"

# Create the engine
engine = create_engine(
url,
connect_args={"sslmode": "verify-full", "sslrootcert": "./root.pem"},
)

engine = create_engine(url, connect_args=connect_args)

# Adds a listener that creates a new token every time a new connection is created in the SQLAlchemy engine
@event.listens_for(engine, "do_connect")
def add_token_to_params(dialect, conn_rec, cargs, cparams):
Expand Down
Loading