Registry / gcp / cloud-sql-python-connector

cloud-sql-python-connector

JSON →
library1.22.0pypypi✓ verified 25d ago

The Google Cloud SQL Python Connector is a client library that helps connect Python applications to Google Cloud SQL databases. It automatically handles authentication, encryption, and secure connection management, acting as a smart proxy for your database connections. As of version 1.20.1, it provides robust and secure connectivity. The library is actively maintained by Google, with frequent updates aligning with Cloud SQL proxy and client library best practices.

pip install cloud-sql-python-connector[pymysql]
INSTALL
IMPORT
SIG · CLOUD-SQL-PYTHON-C
C
cloud-sql-python-connector
gcppythonv1.22.0
Install
8.0s avg
Import
1207ms
Disk
80MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.22.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.915 runs
installs and imports cleanly · install 0.0s · import 1.260s · 80.1MB
glibc
py 3.103.915 runs
installs and imports cleanly · install 8.0s · import 1.153s · 80MB
80MB installed
● package 80MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Connector
from google.cloud.sql.connector import Connector
IPTypes
from google.cloud.sql.connector import IPTypes

This quickstart demonstrates connecting to a MySQL Cloud SQL instance using PyMySQL. It relies on environment variables for sensitive information and the instance connection name. Ensure you have the `cloud-sql-python-connector[pymysql]` package installed. The connector automatically handles authentication using Application Default Credentials (ADC) or a service account key specified by `GOOGLE_APPLICATION_CREDENTIALS`.

import os import pymysql from google.cloud.sql.connector import Connector, IPTypes # Recommended: Use Application Default Credentials (ADC). # Ensure GOOGLE_APPLICATION_CREDENTIALS env var is set or ADC is configured. # Initialize Connector connector = Connector() # Function to get a database connection def get_db_connection(): try: conn = connector.connect( os.environ.get("INSTANCE_CONNECTION_NAME", "your-project:your-region:your-instance"), "pymysql", # Specify the DBAPI module you are using user=os.environ.get("DB_USER", "root"), password=os.environ.get("DB_PASS", ""), db=os.environ.get("DB_NAME", "my_database"), ip_type=IPTypes.PUBLIC if os.environ.get("IP_TYPE", "public").lower() == "public" else IPTypes.PRIVATE ) return conn except Exception as e: print(f"Error creating database connection: {e}") return None # Example Usage: if __name__ == "__main__": # Set environment variables for testing, or rely on actual deployment configs. # os.environ['INSTANCE_CONNECTION_NAME'] = 'your-project:your-region:your-instance' # os.environ['DB_USER'] = 'my_user' # os.environ['DB_PASS'] = 'my_password' # os.environ['DB_NAME'] = 'my_database' # os.environ['IP_TYPE'] = 'public' # or 'private' conn = None try: conn = get_db_connection() if conn: with conn.cursor() as cursor: cursor.execute("SELECT 1 + 1 AS solution;") result = cursor.fetchone() print(f"Database connection successful! Result: {result}") except Exception as e: print(f"An error occurred during database operation: {e}") finally: if conn: conn.close() connector.close() # Important: close the connector when your application exits
Debug
Known issues
breakingMajor breaking changes occurred in version 1.0.0. The primary connection method was renamed from `create_connection` to `connect`, and the `database_driver` argument was removed in favor of passing the DBAPI module object (e.g., `pymysql`) directly.
fix
Update your code to use `connector.connect(instance_connection_name, dbapi_module, ...)` and ensure you pass the DBAPI module (e.g., `pymysql`) as the second argument.
affects: <1.0.0
breakingThe `refresh_delay` parameter in the `Connector` constructor was removed, as its functionality is now handled internally and dynamically by the library.
fix
Remove the `refresh_delay` parameter and its value from your `Connector` constructor calls. The library will manage token refreshes automatically.
affects: >=1.15.0
gotchaYou must install the appropriate database driver extra (e.g., `[pymysql]`, `[pg8000]`, `[psycopg2]`) when installing the connector, otherwise, connection attempts will fail with module not found errors.
fix
Install the connector with the correct extra: `pip install cloud-sql-python-connector[<driver>]`. For example, `pip install cloud-sql-python-connector[pymysql]`.
affects: All versions
gotchaIncorrect `instance_connection_name` format. The correct format is `PROJECT_ID:REGION:INSTANCE_NAME`. Using just `INSTANCE_NAME` or other variations will lead to connection failures.
fix
Always provide the full instance connection name in `PROJECT_ID:REGION:INSTANCE_NAME` format, typically retrieved from the Cloud SQL instance details in the Google Cloud Console.
affects: All versions
gotchaApplication Default Credentials (ADC) were not found. The Cloud SQL Python Connector relies on ADC for authentication to Google Cloud. Ensure your environment is configured with valid credentials.
fix
Set up Application Default Credentials by following the instructions at https://cloud.google.com/docs/authentication/external/set-up-adc. This often involves running `gcloud auth application-default login` or setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable.
affects: All versions
gotchaThe `cloud-sql-python-connector` library requires valid Google Cloud authentication credentials (e.g., via Application Default Credentials (ADC) or explicitly provided service account credentials). Without them, initialization or connection attempts will fail with a `DefaultCredentialsError`.
fix
Ensure your environment is authenticated with Google Cloud, typically by setting up Application Default Credentials (ADC). This can be done by running `gcloud auth application-default login` if using the Google Cloud SDK, or by setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to the path of a service account key file.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'google.cloud.sql.connector'
The `cloud-sql-python-connector` library or its parent `google` namespace package is not installed or not available in the Python environment. This often happens due to a missing entry in `requirements.txt` for deployments or an incorrect `pip install` command.
fix
Ensure the `cloud-sql-python-connector` package is installed with its required database driver. For example, for MySQL: `pip install "cloud-sql-python-connector[pymysql]"`. For PostgreSQL: `pip install "cloud-sql-python-connector[pg8000]"` or `pip install "cloud-sql-python-connector[asyncpg]"`. Make sure this is included in your `requirements.txt` if deploying.
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1045, “Access denied for user 'your_user'@'cloudsqlproxy~'localIP' (using password: NO)”)
The database user, password, or IAM permissions are incorrect or insufficient for the connecting principal (user or service account) to access the Cloud SQL instance. This can also happen if the service account lacks the `cloudsql.client` role.
fix
Verify the database username and password are correct for the SQL user. If using IAM authentication, ensure the service account or user has the `Cloud SQL Client` IAM role on the Google Cloud Project and is added as an IAM database user on the Cloud SQL instance.
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/cloudsql/<instance-connection-name>/.s.PGSQL.5432"?
This error occurs when the application attempts to connect via a Unix domain socket, but the Cloud SQL Auth Proxy is not running, is misconfigured, or the instance connection name in the connection string is incorrect.
fix
Ensure the Cloud SQL Auth Proxy is running and correctly creating the Unix socket for your instance. Verify that the `instance_connection_name` (e.g., `project-id:region:instance-name`) in your application's connection string or environment variables (e.g., `CLOUD_SQL_INSTANCE_CONNECTION_NAME`) is exact. On platforms like App Engine Flex, ensure `cloud_sql_instances` is configured in `app.yaml`.
ERROR: Could not find a version that satisfies the requirement google-cloud-sql-connector (from versions: none) ERROR: No matching distribution found for google-cloud-sql-connector.
The package name used in `pip install` or `requirements.txt` is incorrect. The correct package name is `cloud-sql-python-connector`, not `google-cloud-sql-connector`. This can also occur if the base Docker image (e.g., Alpine Linux) lacks necessary system dependencies for the connector or its database drivers.
fix
Correct the package name to `cloud-sql-python-connector` in your `pip install` command or `requirements.txt`. For example, `pip install "cloud-sql-python-connector[DRIVER]"`. If using a slim Docker image (like Alpine), consider switching to a Debian-based image or explicitly installing build dependencies.
Upgrade
Version history
1.22.0latest on PyPI · released Aug 18, 2026
Audit
Dependencies
pymysqloptionalRequired for connecting to MySQL databases via a connector extra.
pg8000optionalRequired for connecting to PostgreSQL databases via a connector extra.
psycopg2-binaryoptionalRequired for connecting to PostgreSQL databases via a connector extra (psycopg2-binary is commonly used for ease of installation).
Agent activity
39 hits · last 30 days
node
32
OpenAI (training)
1
Resources
cloud-sql-python-connector — pip install cloud-sql-python-connector · libregistry