Connecting to Cloud SQL using Python is not always straightforward. Depending on the context, sometimes you have to connect to a Unix domain socket, sometimes you have to allow-list IP addresses for TCP connections, or sometimes you have to run the Cloud SQL Auth proxy locally. Making these connections secure is yet another challenge: you might have to manage SSL certificates, firewalls rules, IP addresses, etc. Fortunately, there is an easier way.
Enter theCloud SQL Python Connector, a Python package that makes connecting to Cloud SQL both easy and secure for all three supported database engines (Postgres, MySQL, and SQL Server), from anywhere (local machine, Cloud Run, App Engine, Cloud Functions, etc.).
The Python Connector is one of the Cloud SQL connector libraries (also available in tasty Java and Go flavors).
The Cloud SQL connector libraries provide the following benefits:
IAM Authorization: the connectors use IAM permissions to control who and what can connect to your Cloud SQL instances.
Improved Security: the connectors use robust, updated TLS 1.3 encryption and identity verification between the client connector and the server-side proxy, independent of the database protocol.Convenience: the connectors remove the requirement to use and distribute SSL certificates, manage firewalls or source/destination IP addresses.IAM Database Authentication(optional): the connectors provide support forCloud SQL’s automatic IAM database authentication feature.
Try it out with demo notebooks
We’ve created interactive Colab notebooks that show you how to use the Cloud SQL Python Connector – all without needing to write a single line of code yourself! The notebooks will automatically use a supported database driver based on the database engine you are using with Cloud SQL.
PostgreSQL Notebook, using pg8000MySQL Notebook, using pymysqlSQL Server Notebook, using pytds
Python Connector Notebook
With the Cloud SQL Python Connector you can now easily connect to Cloud SQL from Python securely and conveniently. You can even leverage automatic IAM database authentication to access Cloud SQL as your IAM authenticated user or service account!
Want to learn even more? Check out the resources below to dive in:
Cloud SQL Python Connector GithubPython Connector Flask Application Sample
Cloud BlogRead More