{"id":15221609,"url":"https://github.com/googlecloudplatform/cloud-sql-python-connector","last_synced_at":"2025-05-14T12:13:02.243Z","repository":{"id":37821360,"uuid":"193736469","full_name":"GoogleCloudPlatform/cloud-sql-python-connector","owner":"GoogleCloudPlatform","description":"A Python library for connecting securely to your Cloud SQL instances.","archived":false,"fork":false,"pushed_at":"2025-04-09T19:02:57.000Z","size":2059,"stargazers_count":305,"open_issues_count":41,"forks_count":75,"subscribers_count":30,"default_branch":"main","last_synced_at":"2025-04-11T16:23:43.118Z","etag":null,"topics":["cloud-sql","libraries","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GoogleCloudPlatform.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-06-25T15:38:03.000Z","updated_at":"2025-04-09T18:46:29.000Z","dependencies_parsed_at":"2023-09-28T18:47:48.221Z","dependency_job_id":"f953c224-be18-4815-a511-26eab218091a","html_url":"https://github.com/GoogleCloudPlatform/cloud-sql-python-connector","commit_stats":{"total_commits":741,"total_committers":22,"mean_commits":33.68181818181818,"dds":0.4939271255060729,"last_synced_commit":"d1510f656c14ec3f724ed8d847ec554ce53e5696"},"previous_names":[],"tags_count":45,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleCloudPlatform%2Fcloud-sql-python-connector","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleCloudPlatform%2Fcloud-sql-python-connector/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleCloudPlatform%2Fcloud-sql-python-connector/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleCloudPlatform%2Fcloud-sql-python-connector/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GoogleCloudPlatform","download_url":"https://codeload.github.com/GoogleCloudPlatform/cloud-sql-python-connector/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248438720,"owners_count":21103462,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cloud-sql","libraries","python"],"created_at":"2024-09-28T15:06:25.301Z","updated_at":"2025-04-11T16:23:55.917Z","avatar_url":"https://github.com/GoogleCloudPlatform.png","language":"Python","readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://cloud.google.com/blog/topics/developers-practitioners/how-connect-cloud-sql-using-python-easy-way\"\u003e\n        \u003cimg src=\"https://raw.githubusercontent.com/GoogleCloudPlatform/cloud-sql-python-connector/main/docs/images/cloud-sql-python-connector.png\" alt=\"cloud-sql-python-connector image\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n\u003ch1 align=\"center\"\u003eCloud SQL Python Connector\u003c/h1\u003e\n\n[![Open In Colab][colab-badge]][colab-notebook]\n[![CI][ci-badge]][ci-build]\n[![pypi][pypi-badge]][pypi-docs]\n[![PyPI download month][pypi-downloads]][pypi-docs]\n[![python][python-versions]][pypi-docs]\n\n[colab-badge]: https://colab.research.google.com/assets/colab-badge.svg\n[colab-notebook]: https://colab.research.google.com/github/GoogleCloudPlatform/cloud-sql-python-connector/blob/main/samples/notebooks/postgres_python_connector.ipynb\n[ci-badge]: https://github.com/GoogleCloudPlatform/cloud-sql-python-connector/actions/workflows/tests.yml/badge.svg?event=push\n[ci-build]: https://github.com/GoogleCloudPlatform/cloud-sql-python-connector/actions/workflows/tests.yml?query=event%3Apush+branch%3Amain\n[pypi-badge]: https://img.shields.io/pypi/v/cloud-sql-python-connector\n[pypi-docs]: https://pypi.org/project/cloud-sql-python-connector\n[pypi-downloads]: https://img.shields.io/pypi/dm/cloud-sql-python-connector.svg\n[python-versions]: https://img.shields.io/pypi/pyversions/cloud-sql-python-connector\n\nThe _Cloud SQL Python Connector_ is a Cloud SQL connector designed for use with the\nPython language. Using a Cloud SQL connector provides a native alternative to the\n[Cloud SQL Auth Proxy](https://cloud.google.com/sql/docs/mysql/sql-proxy) while\nproviding the following benefits:\n\n* **IAM Authorization:** uses IAM permissions to control who/what can connect to\n  your Cloud SQL instances\n* **Improved Security:** uses robust, updated TLS 1.3 encryption and\n  identity verification between the client connector and the server-side proxy,\n  independent of the database protocol.\n* **Convenience:** removes the requirement to use and distribute SSL\n  certificates, as well as manage firewalls or source/destination IP addresses.\n* (optionally) **IAM DB Authentication:** provides support for\n  [Cloud SQL’s automatic IAM DB AuthN][iam-db-authn] feature.\n\n[iam-db-authn]: https://cloud.google.com/sql/docs/postgres/authentication\n\nThe Cloud SQL Python Connector is a package to be used alongside a database driver.\nCurrently supported drivers are:\n - [`pymysql`](https://github.com/PyMySQL/PyMySQL) (MySQL)\n - [`pg8000`](https://github.com/tlocke/pg8000) (PostgreSQL)\n - [`asyncpg`](https://github.com/MagicStack/asyncpg) (PostgreSQL)\n - [`pytds`](https://github.com/denisenkom/pytds) (SQL Server)\n\n\n## Installation\n\nYou can install this library with `pip install`, specifying the driver\nbased on your database dialect.\n\n### MySQL\n```\npip install \"cloud-sql-python-connector[pymysql]\"\n```\n### Postgres\nThere are two different database drivers that are supported for the Postgres dialect:\n\n#### pg8000\n```\npip install \"cloud-sql-python-connector[pg8000]\"\n```\n#### asyncpg\n```\npip install \"cloud-sql-python-connector[asyncpg]\"\n```\n### SQL Server\n```\npip install \"cloud-sql-python-connector[pytds]\"\n```\n\n### APIs and Services\n\nThis package requires the following to successfully make Cloud SQL Connections:\n\n- IAM principal (user, service account, etc.) with the\n[Cloud SQL Client][client-role] role. This IAM principal will be used for\n[credentials](#credentials).\n- The [Cloud SQL Admin API][admin-api] to be enabled within your Google Cloud\nProject. By default, the API will be called in the project associated with\nthe IAM principal.\n\n[admin-api]: https://console.cloud.google.com/apis/api/sqladmin.googleapis.com\n[client-role]: https://cloud.google.com/sql/docs/mysql/roles-and-permissions\n\n### Credentials\n\nThis library uses the [Application Default Credentials (ADC)][adc] strategy for\nresolving credentials. Please see [these instructions for how to set your ADC][set-adc]\n(Google Cloud Application vs Local Development, IAM user vs service account credentials),\nor consult the [google.auth][google-auth] package.\n\nTo explicitly set a specific source for the credentials, see\n[Configuring the Connector](#configuring-the-connector) below.\n\n[adc]: https://cloud.google.com/docs/authentication#adc\n[set-adc]: https://cloud.google.com/docs/authentication/provide-credentials-adc\n[google-auth]: https://google-auth.readthedocs.io/en/master/reference/google.auth.html\n\n## Usage\n\nThis package provides several functions for authorizing and encrypting\nconnections. These functions are used with your database driver to connect to\nyour Cloud SQL instance.\n\nThe instance connection name for your Cloud SQL instance is always in the\nformat \"project:region:instance\".\n\n### How to use this Connector\n\nTo connect to Cloud SQL using the connector, inititalize a `Connector`\nobject and call its `connect` method with the proper input parameters.\n\nThe `Connector` itself creates connection objects by calling its `connect` method but does not manage database connection pooling. For this reason, it is recommended to use the connector alongside a library that can create connection pools, such as [SQLAlchemy](https://www.sqlalchemy.org/). This will allow for connections to remain open and be reused, reducing connection overhead and the number of connections needed.\n\nIn the Connector's `connect` method below, 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.\n\nTo use this connector with SQLAlchemy, use the `creator` argument for `sqlalchemy.create_engine`:\n\n```python\nfrom google.cloud.sql.connector import Connector\nimport sqlalchemy\n\n# initialize Connector object\nconnector = Connector()\n\n# initialize SQLAlchemy connection pool with Connector\npool = sqlalchemy.create_engine(\n    \"mysql+pymysql://\",\n    creator=lambda: connector.connect(\n        \"project:region:instance\",\n        \"pymysql\",\n        user=\"my-user\",\n        password=\"my-password\",\n        db=\"my-db-name\"\n    ),\n)\n```\n\nThe returned connection pool engine can then be used to query and modify the database.\n\n```python\n# insert statement\ninsert_stmt = sqlalchemy.text(\n    \"INSERT INTO my_table (id, title) VALUES (:id, :title)\",\n)\n\nwith pool.connect() as db_conn:\n    # insert into database\n    db_conn.execute(insert_stmt, parameters={\"id\": \"book1\", \"title\": \"Book One\"})\n\n    # query database\n    result = db_conn.execute(sqlalchemy.text(\"SELECT * from my_table\")).fetchall()\n\n    # commit transaction (SQLAlchemy v2.X.X is commit as you go)\n    db_conn.commit()\n\n    # Do something with the results\n    for row in result:\n        print(row)\n```\n\nTo close the `Connector` object's background resources, call its `close()` method as follows:\n\n```python\nconnector.close()\n```\n\n\u003e [!NOTE]\n\u003e\n\u003e For more examples of using SQLAlchemy to manage connection pooling with the connector,\n\u003e please see [Cloud SQL SQLAlchemy Samples](https://cloud.google.com/sql/docs/postgres/connect-connectors#python_1).\n\n### Configuring the Connector\n\nIf you need to customize something about the connector, or want to specify\ndefaults for each connection to make, you can initialize a\n`Connector` object as follows:\n\n```python\nfrom google.cloud.sql.connector import Connector\n\n# Note: all parameters below are optional\nconnector = Connector(\n    ip_type=\"public\",  # can also be \"private\" or \"psc\"\n    enable_iam_auth=False,\n    timeout=30,\n    credentials=custom_creds, # google.auth.credentials.Credentials\n    refresh_strategy=\"lazy\",  # can be \"lazy\" or \"background\"\n)\n```\n\n### Using Connector as a Context Manager\n\nThe `Connector` object can also be used as a context manager in order to\nautomatically close and cleanup resources, removing the need for explicit\ncalls to `connector.close()`.\n\nConnector as a context manager:\n\n```python\nfrom google.cloud.sql.connector import Connector\nimport sqlalchemy\n\n# initialize Cloud SQL Python Connector as context manager\nwith Connector() as connector:\n    # initialize SQLAlchemy connection pool with Connector\n    pool = sqlalchemy.create_engine(\n        \"mysql+pymysql://\",\n        creator=lambda: connector.connect(\n            \"project:region:instance\",\n            \"pymysql\",\n            user=\"my-user\",\n            password=\"my-password\",\n            db=\"my-db-name\"\n        ),\n    )\n    # insert statement\n    insert_stmt = sqlalchemy.text(\n        \"INSERT INTO my_table (id, title) VALUES (:id, :title)\",\n    )\n\n    # interact with Cloud SQL database using connection pool\n    with pool.connect() as db_conn:\n        # insert into database\n        db_conn.execute(insert_stmt, parameters={\"id\": \"book1\", \"title\": \"Book One\"})\n\n        # commit transaction (SQLAlchemy v2.X.X is commit as you go)\n        db_conn.commit()\n\n        # query database\n        result = db_conn.execute(sqlalchemy.text(\"SELECT * from my_table\")).fetchall()\n\n        # Do something with the results\n        for row in result:\n            print(row)\n```\n\n### Configuring a Lazy Refresh (Cloud Run, Cloud Functions etc.)\n\nThe Connector's `refresh_strategy` argument can be set to `\"lazy\"` to configure\nthe Python Connector to retrieve connection info lazily and as-needed.\nOtherwise, a background refresh cycle runs to retrive the connection info\nperiodically. This setting is useful in environments where the CPU may be\nthrottled outside of a request context, e.g., Cloud Run, Cloud Functions, etc.\n\nTo set the refresh strategy, set the `refresh_strategy` keyword argument when\ninitializing a `Connector`:\n\n```python\nconnector = Connector(refresh_strategy=\"lazy\")\n```\n\n### Specifying IP Address Type\n\nThe Cloud SQL Python Connector can be used to connect to Cloud SQL instances\nusing both public and private IP addresses, as well as\n[Private Service Connect][psc] (PSC). To specify which IP address type to connect\nwith, set the `ip_type` keyword argument when initializing a `Connector()` or when\ncalling `connector.connect()`.\n\nPossible values for `ip_type` are `\"public\"` (default value),\n`\"private\"`, and `\"psc\"`.\n\nExample:\n\n```python\nconn = connector.connect(\n    \"project:region:instance\",\n    \"pymysql\",\n    ip_type=\"private\"  # use private IP\n... insert other kwargs ...\n)\n```\n\n\u003e [!IMPORTANT]\n\u003e\n\u003e If specifying Private IP or Private Service Connect (PSC), your application must be\n\u003e attached to the proper VPC network to connect to your Cloud SQL instance. For most\n\u003e applications this will require the use of a [VPC Connector][vpc-connector].\n\n[psc]: https://cloud.google.com/vpc/docs/private-service-connect\n[vpc-connector]: https://cloud.google.com/vpc/docs/configure-serverless-vpc-access#create-connector\n\n### Automatic IAM Database Authentication\n\nConnections using [Automatic IAM database authentication](https://cloud.google.com/sql/docs/postgres/authentication#automatic) are supported when using Postgres or MySQL drivers.\nFirst, make sure to [configure your Cloud SQL Instance to allow IAM authentication](https://cloud.google.com/sql/docs/postgres/create-edit-iam-instances#configure-iam-db-instance)\nand [add an IAM database user](https://cloud.google.com/sql/docs/postgres/create-manage-iam-users#creating-a-database-user).\n\nNow, you can connect using user or service account credentials instead of a password.\nIn the call to connect, set the `enable_iam_auth` keyword argument to true and the `user` argument to the appropriately formatted IAM principal.\n\u003e Postgres: For an IAM user account, this is the user's email address. For a service account, it is the service account's email without the `.gserviceaccount.com` domain suffix.\n\n\u003e MySQL: For an IAM user account, this is the user's email address, without the @ or domain name. For example, for `test-user@gmail.com`, set the `user` argument to `test-user`. For a service account, this is the service account's email address without the `@project-id.iam.gserviceaccount.com` suffix.\n\nExample:\n\n```python\nconn = connector.connect(\n     \"project:region:instance\",\n     \"pg8000\",\n     user=\"postgres-iam-user@gmail.com\",\n     db=\"my-db-name\",\n     enable_iam_auth=True,\n )\n```\n\n### SQL Server (MSSQL)\n\n\u003e [!IMPORTANT]\n\u003e\n\u003e If your SQL Server instance is set to [enforce SSL connections](https://cloud.google.com/sql/docs/sqlserver/configure-ssl-instance#enforcing-ssl),\n\u003e you need to download the CA certificate for your instance and include `cafile={path to downloaded certificate}`\n\u003e and `validate_host=False`. This is a workaround for a [known issue](https://issuetracker.google.com/184867147).\n\n#### Active Directory Authentication\n\nActive Directory authentication for SQL Server instances is currently only supported on Windows.\nFirst, make sure to follow [these steps](https://cloud.google.com/blog/topics/developers-practitioners/creating-sql-server-instance-integrated-active-directory-using-google-cloud-sql)\nto set up a Managed AD domain and join your Cloud SQL instance to the domain.\n[See here for more info on Cloud SQL Active Directory integration](https://cloud.google.com/sql/docs/sqlserver/ad).\n\nOnce you have followed the steps linked above, you can run the following code to return a connection object:\n\n```python\nconn = connector.connect(\n    \"project:region:instance\",\n    \"pytds\",\n    db=\"my-db-name\",\n    active_directory_auth=True,\n    server_name=\"public.[instance].[location].[project].cloudsql.[domain]\",\n)\n```\n\nOr, if using Private IP:\n\n```python\nconn = connector.connect(\n    \"project:region:instance\",\n    \"pytds\",\n    db=\"my-db-name\",\n    active_directory_auth=True,\n    server_name=\"private.[instance].[location].[project].cloudsql.[domain]\",\n    ip_type=\"private\"\n)\n```\n\n### Using DNS domain names to identify instances\n\nThe connector can be configured to use DNS to look up an instance. This would\nallow you to configure your application to connect to a database instance, and\ncentrally configure which instance in your DNS zone.\n\n#### Configure your DNS Records\n\nAdd a DNS TXT record for the Cloud SQL instance to a **private** DNS server\nor a private Google Cloud DNS Zone used by your application.\n\n\u003e [!NOTE]\n\u003e\n\u003e You are strongly discouraged from adding DNS records for your\n\u003e Cloud SQL instances to a public DNS server. This would allow anyone on the\n\u003e internet to discover the Cloud SQL instance name.\n\nFor example: suppose you wanted to use the domain name\n`prod-db.mycompany.example.com` to connect to your database instance\n`my-project:region:my-instance`. You would create the following DNS record:\n\n* Record type: `TXT`\n* Name: `prod-db.mycompany.example.com` – This is the domain name used by the application\n* Value: `my-project:my-region:my-instance` – This is the Cloud SQL instance connection name\n\n#### Configure the connector\n\nConfigure the connector to resolve DNS names by initializing it with\n`resolver=DnsResolver` and replacing the instance connection name with the DNS\nname in `connector.connect`:\n\n```python\nfrom google.cloud.sql.connector import Connector, DnsResolver\nimport pymysql\nimport sqlalchemy\n\n# initialize Cloud SQL Python Connector with `resolver=DnsResolver`\nwith Connector(resolver=DnsResolver) as connector:\n    # initialize SQLAlchemy connection pool with Connector\n    pool = sqlalchemy.create_engine(\n        \"mysql+pymysql://\",\n        creator=lambda: connector.connect(\n            \"prod-db.mycompany.example.com\",  # using DNS name\n            \"pymysql\",\n            user=\"my-user\",\n            password=\"my-password\",\n            db=\"my-db-name\"\n        ),\n    )\n    # ... use SQLAlchemy engine normally\n```\n\n### Automatic failover using DNS domain names\n\n\u003e [!NOTE]\n\u003e\n\u003e Usage of the `asyncpg` driver does not currently support automatic failover.\n\nWhen the connector is configured using a domain name, the connector will\nperiodically check if the DNS record for an instance changes. When the connector\ndetects that the domain name refers to a different instance, the connector will\nclose all open connections to the old instance. Subsequent connection attempts\nwill be directed to the new instance.\n\nFor example: suppose application is configured to connect using the\ndomain name `prod-db.mycompany.example.com`. Initially the private DNS\nzone has a TXT record with the value `my-project:region:my-instance`. The\napplication establishes connections to the `my-project:region:my-instance`\nCloud SQL instance.\n\nThen, to reconfigure the application to use a different database\ninstance, change the value of the `prod-db.mycompany.example.com` DNS record\nfrom `my-project:region:my-instance` to `my-project:other-region:my-instance-2`\n\nThe connector inside the application detects the change to this\nDNS record. Now, when the application connects to its database using the\ndomain name `prod-db.mycompany.example.com`, it will connect to the\n`my-project:other-region:my-instance-2` Cloud SQL instance.\n\nThe connector will automatically close all existing connections to\n`my-project:region:my-instance`. This will force the connection pools to\nestablish new connections. Also, it may cause database queries in progress\nto fail.\n\nThe connector will poll for changes to the DNS name every 30 seconds by default.\nYou may configure the frequency of the connections using the Connector's\n`failover_period` argument (i.e. `Connector(failover_period=60`). When this is\nset to 0, the connector will disable polling and only check if the DNS record\nchanged when it is creating a new connection.\n\n### Using the Python Connector with Python Web Frameworks\n\nThe Python Connector can be used alongside popular Python web frameworks such\nas Flask, FastAPI, etc, to integrate Cloud SQL databases within your\nweb applications.\n\n\u003e [!NOTE]\n\u003e\n\u003e For serverless environments such as Cloud Functions, Cloud Run, etc, it may be\n\u003e beneficial to initialize the `Connector` with the lazy refresh strategy.\n\u003e i.e. `Connector(refresh_strategy=\"lazy\")`\n\u003e\n\u003e See [Configuring a Lazy Refresh](#configuring-a-lazy-refresh-cloud-run-cloud-functions-etc)\n\n#### Flask-SQLAlchemy\n\n[Flask-SQLAlchemy](https://flask-sqlalchemy.palletsprojects.com/en/2.x/)\nis an extension for [Flask](https://flask.palletsprojects.com/en/2.2.x/)\nthat adds support for [SQLAlchemy](https://www.sqlalchemy.org/) to your\napplication. It aims to simplify using SQLAlchemy with Flask by providing\nuseful defaults and extra helpers that make it easier to accomplish\ncommon tasks.\n\nYou can configure Flask-SQLAlchemy to connect to a Cloud SQL database from\nyour web application through the following:\n\n```python\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom google.cloud.sql.connector import Connector\n\n\n# initialize Python Connector object\nconnector = Connector()\n\napp = Flask(__name__)\n\n# configure Flask-SQLAlchemy to use Python Connector\napp.config['SQLALCHEMY_DATABASE_URI'] = \"postgresql+pg8000://\"\napp.config['SQLALCHEMY_ENGINE_OPTIONS'] = {\n    \"creator\": lambda: conn = connector.connect(\n        \"project:region:instance-name\", # Cloud SQL Instance Connection Name\n        \"pg8000\",\n        user=\"my-user\",\n        password=\"my-password\",\n        db=\"my-database\",\n        ip_type=\"public\"  # \"private\" for private IP\n    )\n}\n\n# initialize the app with the extension\ndb = SQLAlchemy()\ndb.init_app(app)\n```\n\nFor more details on how to use Flask-SQLAlchemy, check out the\n[Flask-SQLAlchemy Quickstarts](https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/quickstart/)\n\n#### FastAPI\n\n[FastAPI](https://fastapi.tiangolo.com/) is a modern, fast (high-performance),\nweb framework for building APIs with Python based on standard Python type hints.\n\nYou can configure FastAPI to connect to a Cloud SQL database from\nyour web application using [SQLAlchemy ORM](https://docs.sqlalchemy.org/en/14/orm/)\nthrough the following:\n\n```python\nimport sqlalchemy\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom google.cloud.sql.connector import Connector\n\n\n# initialize Cloud SQL Python Connector\nconnector = Connector()\n\n# create connection pool engine\nengine = sqlalchemy.create_engine(\n    \"postgresql+pg8000://\",\n    creator=lambda: connector.connect(\n        \"project:region:instance-name\", # Cloud SQL Instance Connection Name\n        \"pg8000\",\n        user=\"my-user\",\n        password=\"my-password\",\n        db=\"my-database\",\n        ip_type=\"public\"  # \"private\" for private IP\n    ),\n)\n\n# create SQLAlchemy ORM session\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\nBase = declarative_base()\n```\n\nTo learn more about integrating a database into your FastAPI application,\nfollow along the [FastAPI SQL Database guide](https://fastapi.tiangolo.com/tutorial/sql-databases/#create-the-database-models).\n\n### Async Driver Usage\n\nThe Cloud SQL Connector is compatible with\n[asyncio](https://docs.python.org/3/library/asyncio.html) to improve the speed\nand efficiency of database connections through concurrency. You can use all\nnon-asyncio drivers through the `Connector.connect_async` function, in addition\nto the following asyncio database drivers:\n- [asyncpg](https://magicstack.github.io/asyncpg) (Postgres)\n\nThe Cloud SQL Connector has a helper `create_async_connector` function that is\nrecommended for asyncio database connections. It returns a `Connector`\nobject that uses the current thread's running event loop. This is different\nthan `Connector()` which by default initializes a new event loop in a\nbackground thread.\n\nThe `create_async_connector` allows all the same input arguments as the\n[Connector](#configuring-the-connector) object.\n\nOnce a `Connector` object is returned by `create_async_connector` you can call\nits `connect_async` method, just as you would the `connect` method:\n\n#### Asyncpg Connection Pool\n\n```python\nimport asyncpg\nfrom google.cloud.sql.connector import Connector, create_async_connector\n\nasync def main():\n    # initialize Connector object for connections to Cloud SQL\n    connector = create_async_connector()\n\n    # creation function to generate asyncpg connections as the 'connect' arg\n    async def getconn(instance_connection_name, **kwargs) -\u003e asyncpg.Connection:\n        return await connector.connect_async(\n            instance_connection_name,\n            \"asyncpg\",\n            user=\"my-user\",\n            password=\"my-password\",\n            db=\"my-db\",\n            **kwargs, # ... additional asyncpg args\n        )\n\n    # initialize connection pool\n    pool = await asyncpg.create_pool(\n        \"my-project:my-region:my-instance\", connect=getconn\n    )\n\n    # acquire connection and query Cloud SQL database\n    async with pool.acquire() as conn:\n        res = await conn.fetch(\"SELECT NOW()\")\n    \n    # close Connector\n    await connector.close_async()\n```\n\n#### SQLAlchemy Async Engine\n\n```python\nimport sqlalchemy\nfrom sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine\n\nfrom google.cloud.sql.connector import Connector, create_async_connector\n\n\nasync def main():\n    # initialize Connector object for connections to Cloud SQL\n    connector = await create_async_connector()\n\n    # The Cloud SQL Python Connector can be used along with SQLAlchemy using the\n    # 'async_creator' argument to 'create_async_engine'\n    pool = create_async_engine(\n        \"postgresql+asyncpg://\",\n        async_creator=lambda: connector.connect_async(\n            \"project:region:instance\",  # Cloud SQL instance connection name\n            \"asyncpg\",\n            user=\"my-user\",\n            password=\"my-password\",\n            db=\"my-db-name\"\n            # ... additional database driver args\n        ),\n    )\n\n    # example query\n    async with pool.connect() as conn:\n        await conn.execute(sqlalchemy.text(\"SELECT NOW()\"))\n\n    # close Connector\n    await connector.close_async()\n\n    # dispose of connection pool\n    await pool.dispose()\n```\n\nFor more details on additional database arguments with an `asyncpg.Connection`\n, please visit the\n[official documentation](https://magicstack.github.io/asyncpg/current/api/index.html).\n\n### Async Context Manager\n\nAn alternative to using the `create_async_connector` function is initializing\na `Connector` as an async context manager, removing the need for explicit\ncalls to `connector.close_async()` to cleanup resources.\n\n\u003e [!NOTE]\n\u003e\n\u003e This alternative requires that the running event loop be\n\u003e passed in as the `loop` argument to `Connector()`.\n\n#### Asyncpg Connection Pool\n\n```python\nimport asyncpg\nfrom google.cloud.sql.connector import Connector, create_async_connector\n\nasync def main():\n    # initialize Connector object for connections to Cloud SQL\n    loop = asyncio.get_running_loop()\n    async with Connector(loop=loop) as connector:\n\n        # creation function to generate asyncpg connections as the 'connect' arg\n        async def getconn(instance_connection_name, **kwargs) -\u003e asyncpg.Connection:\n            return await connector.connect_async(\n                instance_connection_name,\n                \"asyncpg\",\n                user=\"my-user\",\n                password=\"my-password\",\n                db=\"my-db\",\n                **kwargs, # ... additional asyncpg args\n            )\n\n        # create connection pool\n        pool = await asyncpg.create_pool(\n            \"my-project:my-region:my-instance\", connect=getconn\n        )\n\n        # acquire connection and query Cloud SQL database\n        async with pool.acquire() as conn:\n            res = await conn.fetch(\"SELECT NOW()\")\n```\n\n#### SQLAlchemy Async Engine\n\n```python\nimport asyncio\nimport asyncpg\n\nimport sqlalchemy\nfrom sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine\n\nfrom google.cloud.sql.connector import Connector\n\n\nasync def main():\n    # initialize Connector object for connections to Cloud SQL\n    loop = asyncio.get_running_loop()\n    async with Connector(loop=loop) as connector:\n        # The Cloud SQL Python Connector can be used along with SQLAlchemy using the\n        # 'async_creator' argument to 'create_async_engine'\n        pool = create_async_engine(\n            \"postgresql+asyncpg://\",\n            async_creator=lambda: connector.connect_async(\n                \"project:region:instance\",  # Cloud SQL instance connection name\n                \"asyncpg\",\n                user=\"my-user\",\n                password=\"my-password\",\n                db=\"my-db-name\"\n                # ... additional database driver args\n            ),\n        )\n\n        # example query\n        async with pool.connect() as conn:\n            await conn.execute(sqlalchemy.text(\"SELECT NOW()\"))\n\n        # dispose of connection pool\n        await pool.dispose()\n```\n\n### Debug Logging\n\nThe Cloud SQL Python Connector uses the standard [Python logging module][python-logging]\nfor debug logging support.\n\nAdd the below code to your application to enable debug logging with the Cloud SQL\nPython Connector:\n\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(asctime)s [%(levelname)s]: %(message)s\")\nlogger = logging.getLogger(name=\"google.cloud.sql.connector\")\nlogger.setLevel(logging.DEBUG)\n```\n\nFor more details on configuring logging, please refer to the\n[Python logging docs][configure-logging].\n\n[python-logging]: https://docs.python.org/3/library/logging.html\n[configure-logging]: https://docs.python.org/3/howto/logging.html#configuring-logging\n\n## Support policy\n\n### Major version lifecycle\n\nThis project uses [semantic versioning](https://semver.org/), and uses the\nfollowing lifecycle regarding support for a major version:\n\n**Active** - Active versions get all new features and security fixes (that\nwouldn’t otherwise introduce a breaking change). New major versions are\nguaranteed to be \"active\" for a minimum of 1 year.\n**Deprecated** - Deprecated versions continue to receive security and critical\nbug fixes, but do not receive new features. Deprecated versions will be publicly\nsupported for 1 year.\n**Unsupported** - Any major version that has been deprecated for \u003e=1 year is\nconsidered publicly unsupported.\n\n### Supported Python Versions\n\nWe follow the [Python Version Support Policy][pyver] used by Google Cloud\nLibraries for Python. Changes in supported Python versions will be\nconsidered a minor change, and will be listed in the release notes.\n\n[pyver]: https://cloud.google.com/python/docs/supported-python-versions\n\n### Release cadence\nThis project aims for a minimum monthly release cadence. If no new\nfeatures or fixes have been added, a new PATCH version with the latest\ndependencies is released.\n\n### Contributing\n\nWe welcome outside contributions. Please see our\n[Contributing Guide](CONTRIBUTING.md) for details on how best to contribute.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgooglecloudplatform%2Fcloud-sql-python-connector","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgooglecloudplatform%2Fcloud-sql-python-connector","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgooglecloudplatform%2Fcloud-sql-python-connector/lists"}