Skip to main content

The Cloud SQL Python Connector is a library that can be used alongside a database driver to allow users with sufficient permissions to connect to a Cloud SQL database without having to manually allowlist IPs or manage SSL certificates.

Project description

Cloud SQL Connector for Python Drivers

Warning: This project is currently in alpha, and releases may contain breaking API changes.

The Cloud SQL Python Connector is a library that can be used alongside a database driver to allow users with sufficient permissions to connect to a Cloud SQL database without having to manually allowlist IPs or manage SSL certificates.

Currently supported drivers are

Supported Python Versions

Currently Python versions >= 3.6 are supported.

Authentication

This library uses the Application Default Credentials to authenticate the connection to the Cloud SQL server. For more details, see the previously mentioned link.

To activate credentials locally, use the following gcloud command:

gcloud auth application-default login

How to install this connector

Install latest release from PyPI

Upgrade to the latest version of pip, then run the following command, replacing driver with one of the driver names listed above.

pip install cloud-sql-python-connector[driver]

For example, to use the Python connector with pymysql, run pip install cloud-sql-python-connector[pymysql]

Install dev version

Clone this repo, cd into the cloud-sql-python-connector directory then run the following command to install the package:

pip install .

Conversely, install straight from Github using pip:

pip install git+https://github.com/GoogleCloudPlatform/cloud-sql-python-connector

How to use this connector

To use the connector: import the connector by including the following statement at the top of your Python file:

from google.cloud.sql.connector import connector

Use the connector to create a connection object by calling the connect method. Input your connection string as the first positional argument and the name of the database driver for the second positional argument. Insert the rest of your connection keyword arguments like user, password and database. You can also set the optional timeout or ip_type keyword arguments.

conn = connector.connect(
    "project:region:instance", 
    "pymysql",
    user="root",
    password="shhh",
    db="your-db-name"
... insert other kwargs ...
)

The returned DB-API 2.0 compliant connection object can then be used to query and modify the database:

# Execute a query
cursor = conn.cursor()
cursor.execute("SELECT * from my_table")

# Fetch the results
result = cursor.fetchall()

# Do something with the results
for row in result:
    print(row)

To use this connector with SQLAlchemy, use the creator argument for sqlalchemy.create_engine:

def getconn() -> pymysql.connections.Connection:
    conn: pymysql.connections.Connection = connector.connect(
        "project:region:instance",
        "pymysql",
        user="root",
        password="shhh",
        db="your-db-name"
    )
    return conn

engine = sqlalchemy.create_engine(
    "mysql+pymysql://",
    creator=getconn,
)

Note for SQL Server users: If your SQL Server instance requires SSL, you need to download the CA certificate for your instance and include cafile={path to downloaded certificate} and validate_host=False. This is a workaround for a known issue.

Specifying Public or Private IP

The Cloud SQL Connector for Python can be used to connect to Cloud SQL instances using both public and private IP addresses. To specify which IP address to use to connect, set the ip_type keyword argument Possible values are IPTypes.PUBLIC and IPTypes.PRIVATE. Example:

connector.connect(
    "project:region:instance", 
    "pymysql",
    ip_types=IPTypes.PRIVATE # Prefer private IP
... insert other kwargs ...
)

Note: If specifying Private IP, your application must already be in the same VPC network as your Cloud SQL Instance.

IAM Authentication

Connections using IAM database authentication are supported when using the Postgres driver. First, make sure to configure your Cloud SQL Instance to allow IAM authentication and add an IAM database user. Now, you can connect using user or service account credentials instead of a password. In the call to connect, set the enable_iam_auth keyword argument to true and user to the email address associated with your IAM user. Example:

connector.connect(
     "project:region:instance",
     "pg8000",
     user="postgres-iam-user@gmail.com",
     db="my_database",
     enable_iam_auth=True,
 )

Setup for development

Tests can be run with nox. Change directory into the cloud-sql-python-connector and just run nox to run the tests.

  1. Create a MySQL instance on Google Cloud SQL. Make sure to note your root password when creating the MySQL instance.
  2. When the MySQL instance has finished creating, go to the overview page and set the instance’s connection string to the environment variable MYSQL_CONNECTION_NAME using the following command:
export MYSQL_CONNECTION_NAME=your:connection:string
  1. Enable SSL for your Cloud SQL instance by following these instructions.
  2. Create a service account with Cloud SQL Admin and Cloud SQL Client roles, then download the key and save it in a safe location. Set the path to the json file to the environment variable GOOGLE_APPLICATION_CREDENTIALS using the following command:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/auth/./json
  1. Enable the SQL Admin API.
  2. Clone the repository.
  3. Create a virtual environment and change directory into the cloud-sql-python-connector folder.
  4. Install the package by running the following command:
pip install .

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cloud-sql-python-connector-0.2.0.tar.gz (16.8 kB view details)

Uploaded Source

Built Distribution

cloud_sql_python_connector-0.2.0-py2.py3-none-any.whl (20.7 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file cloud-sql-python-connector-0.2.0.tar.gz.

File metadata

  • Download URL: cloud-sql-python-connector-0.2.0.tar.gz
  • Upload date:
  • Size: 16.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.4.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.0 CPython/3.8.10

File hashes

Hashes for cloud-sql-python-connector-0.2.0.tar.gz
Algorithm Hash digest
SHA256 45d3070984f4318972e5ce7b8fa79fca929a3f1849aac83f2efe4d3eff9974b9
MD5 208da1731425f6dd8431a57757609992
BLAKE2b-256 7f3ab98d6087062a3cf5678bd1fa61f32dc698dd5c5bb17fac21fa153d5e8bd7

See more details on using hashes here.

Provenance

File details

Details for the file cloud_sql_python_connector-0.2.0-py2.py3-none-any.whl.

File metadata

  • Download URL: cloud_sql_python_connector-0.2.0-py2.py3-none-any.whl
  • Upload date:
  • Size: 20.7 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.4.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.0 CPython/3.8.10

File hashes

Hashes for cloud_sql_python_connector-0.2.0-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 63e328fc5c66e0c7f24e8760eab01702c430448c6c635dd4949cabffb833f6e5
MD5 3f4f36894be2cca49b2ad8e2a1e7d708
BLAKE2b-256 3a18b70244b3043f9e405706446a4932f3b22b51757801bad6c19e5c9cd2a88c

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page