Create a TCP connection by using SQLAlchemy

Create a TCP connection to Cloud SQL for PostgreSQL by using SQLAlchemy.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample


# Remember - storing secrets in plaintext is potentially unsafe. Consider using
# something like 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"]

# 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 = db_host
    db_port = os.environ["DB_PORT"]
elif len(host_args) == 2:
    db_hostname, db_port = host_args[0], int(host_args[1])

pool = sqlalchemy.create_engine(
    # Equivalent URL:
    # postgresql+pg8000://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name>
        username=db_user,  # e.g. "my-database-user"
        password=db_pass,  # e.g. "my-database-password"
        host=db_hostname,  # e.g. ""
        port=db_port,  # e.g. 5432
        database=db_name  # e.g. "my-database-name"

What's next

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