<p align="center">
<a href="https://cloud.google.com/alloydb/docs/connect-language-connectors#python-pg8000">
<img src="https://raw.githubusercontent.com/GoogleCloudPlatform/alloydb-python-connector/main/docs/images/alloydb-python-connector.png" alt="alloydb-python-connector image">
</a>
</p>
# AlloyDB Python Connector
[![CI][ci-badge]][ci-build]
[![pypi][pypi-badge]][pypi-docs]
[![python][python-versions]][pypi-docs]
[ci-badge]: https://github.com/GoogleCloudPlatform/alloydb-python-connector/actions/workflows/tests.yaml/badge.svg?event=push
[ci-build]: https://github.com/GoogleCloudPlatform/alloydb-python-connector/actions/workflows/tests.yaml?query=event%3Apush+branch%3Amain
[pypi-badge]: https://img.shields.io/pypi/v/google-cloud-alloydb-connector
[pypi-docs]: https://pypi.org/project/google-cloud-alloydb-connector
[python-versions]: https://img.shields.io/pypi/pyversions/google-cloud-alloydb-connector
The _AlloyDB Python Connector_ is an [AlloyDB](https://cloud.google.com/alloydb)
Connector library designed for use with the Python language.
Using an AlloyDB Connector provides the following benefits:
* **IAM Authorization:** uses IAM permissions to control who/what can connect to
your AlloyDB instances
* **Improved Security:** uses robust, updated TLS 1.3 encryption and
identity verification between the client connector and the server-side proxy,
independent of the database protocol.
* **Convenience:** removes the requirement to use and distribute SSL
certificates, as well as manage firewalls or source/destination IP addresses.
* (optionally) **IAM DB Authentication:** provides support for
[AlloyDB’s automatic IAM DB AuthN][iam-db-authn] feature.
[iam-db-authn]: https://cloud.google.com/alloydb/docs/manage-iam-authn
The AlloyDB Python Connector is a package to be used alongside a database driver.
Currently supported drivers are:
* [`pg8000`](https://github.com/tlocke/pg8000)
* [`asyncpg`](https://magicstack.github.io/asyncpg)
## Installation
You can install this library with `pip install`:
### pg8000
```sh
pip install "google-cloud-alloydb-connector[pg8000]"
```
See [Synchronous Driver Usage](#synchronous-driver-usage) for details.
### asyncpg
```sh
pip install "google-cloud-alloydb-connector[asyncpg]"
```
See [Async Driver Usage](#async-driver-usage) for details.
### APIs and Services
This package requires the following to connect successfully:
* IAM principal (user, service account, etc.) with the [AlloyDB
Client][client-role] role or equivalent. [Credentials](#credentials)
for the IAM principal are used to authorize connections to an AlloyDB instance.
* The [AlloyDB API][alloydb-api] to be enabled within your Google Cloud
Project. By default, the API will be called in the project associated with the
IAM principal.
[alloydb-api]: https://console.cloud.google.com/apis/api/alloydb.googleapis.com
[client-role]: https://cloud.google.com/alloydb/docs/auth-proxy/overview#how-authorized
### Credentials
This library uses the [Application Default Credentials (ADC)][adc] strategy for
resolving credentials. Please see [these instructions for how to set your ADC][set-adc]
(Google Cloud Application vs Local Development, IAM user vs service account credentials),
or consult the [google.auth][google-auth] package.
[adc]: https://cloud.google.com/docs/authentication#adc
[set-adc]: https://cloud.google.com/docs/authentication/provide-credentials-adc
[google-auth]: https://google-auth.readthedocs.io/en/master/reference/google.auth.html
## Usage
This package provides several functions for authorizing and encrypting
connections. These functions are used with your database driver to connect to
your AlloyDB instance.
AlloyDB supports network connectivity through public IP addresses and private,
internal IP addresses, as well as [Private Service Connect][psc] (PSC).
By default this package will attempt to connect over a
private IP connection. When doing so, this package must be run in an
environment that is connected to the [VPC Network][vpc] that hosts your
AlloyDB private IP address.
Please see [Configuring AlloyDB Connectivity][alloydb-connectivity] for more details.
[vpc]: https://cloud.google.com/vpc/docs/vpc
[alloydb-connectivity]: https://cloud.google.com/alloydb/docs/configure-connectivity
[psc]: https://cloud.google.com/vpc/docs/private-service-connect
### Synchronous Driver Usage
To connect to AlloyDB using the connector, inititalize a `Connector`
object and call it's `connect` method with the proper input parameters.
The `Connector` itself creates database 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.
In the Connector's `connect` method below, input your AlloyDB instance URI 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 `db` etc.
To use this connector with SQLAlchemy, use the `creator` argument for `sqlalchemy.create_engine`:
```python
from google.cloud.alloydb.connector import Connector
import sqlalchemy
# initialize Connector object
connector = Connector()
# function to return the database connection
def getconn():
conn = connector.connect(
"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>",
"pg8000",
user="my-user",
password="my-password",
db="my-db-name"
# NOTE: this assumes private IP by default.
# Add the following keyword arg to use public IP:
# ip_type="PUBLIC"
)
return conn
# create connection pool
pool = sqlalchemy.create_engine(
"postgresql+pg8000://",
creator=getconn,
)
```
The returned connection pool engine can then be used to query and modify the database.
```python
# insert statement
insert_stmt = sqlalchemy.text(
"INSERT INTO my_table (id, title) VALUES (:id, :title)",
)
with pool.connect() as db_conn:
# insert into database
db_conn.execute(insert_stmt, parameters={"id": "book1", "title": "Book One"})
# query database
result = db_conn.execute(sqlalchemy.text("SELECT * from my_table")).fetchall()
# commit transaction (SQLAlchemy v2.X.X is commit as you go)
db_conn.commit()
# Do something with the results
for row in result:
print(row)
```
To close the `Connector` object's background resources, call it's `close()` method as follows:
```python
connector.close()
```
### Synchronous Context Manager
The `Connector` object can also be used as a context manager in order to
automatically close and cleanup resources, removing the need for explicit
calls to `connector.close()`.
Connector as a context manager:
```python
from google.cloud.alloydb.connector import Connector
import sqlalchemy
# helper function to return SQLAlchemy connection pool
def init_connection_pool(connector: Connector) -> sqlalchemy.engine.Engine:
# function used to generate database connection
def getconn():
conn = connector.connect(
"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>",
"pg8000",
user="my-user",
password="my-password",
db="my-db-name"
)
return conn
# create connection pool
pool = sqlalchemy.create_engine(
"postgresql+pg8000://",
creator=getconn,
)
return pool
# initialize Connector as context manager
with Connector() as connector:
# initialize connection pool
pool = init_connection_pool(connector)
# insert statement
insert_stmt = sqlalchemy.text(
"INSERT INTO my_table (id, title) VALUES (:id, :title)",
)
# interact with AlloyDB database using connection pool
with pool.connect() as db_conn:
# insert into database
db_conn.execute(insert_stmt, parameters={"id": "book1", "title": "Book One"})
# commit transaction (SQLAlchemy v2.X.X is commit as you go)
db_conn.commit()
# query database
result = db_conn.execute(sqlalchemy.text("SELECT * from my_table")).fetchall()
# Do something with the results
for row in result:
print(row)
```
### Async Driver Usage
The AlloyDB Connector is compatible with [asyncio][] to improve the speed and
efficiency of database connections through concurrency. The `AsyncConnector`
currently supports the following asyncio database drivers:
- [asyncpg](https://magicstack.github.io/asyncpg)
[asyncio]: https://docs.python.org/3/library/asyncio.html
```python
import asyncpg
import sqlalchemy
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from google.cloud.alloydb.connector import AsyncConnector
async def init_connection_pool(connector: AsyncConnector) -> AsyncEngine:
# initialize Connector object for connections to AlloyDB
async def getconn() -> asyncpg.Connection:
conn: asyncpg.Connection = await connector.connect(
"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>",
"asyncpg",
user="my-user",
password="my-password",
db="my-db-name"
# NOTE: this assumes private IP by default.
# Add the following keyword arg to use public IP:
# ip_type="PUBLIC"
# ... additional database driver args
)
return conn
# The AlloyDB Python Connector can be used along with SQLAlchemy using the
# 'async_creator' argument to 'create_async_engine'
pool = create_async_engine(
"postgresql+asyncpg://",
async_creator=getconn,
)
return pool
async def main():
connector = AsyncConnector()
# initialize connection pool
pool = await init_connection_pool(connector)
# example query
async with pool.connect() as conn:
await conn.execute(sqlalchemy.text("SELECT NOW()"))
# dispose of connection pool
await pool.dispose()
# close Connector
await connector.close()
```
For more details on additional arguments with an `asyncpg.Connection`, please
visit the [official documentation][asyncpg-docs].
[asyncpg-docs]: https://magicstack.github.io/asyncpg/current/api/index.html
### Async Context Manager
The `AsyncConnector` also may be used as an async context manager, removing the
need for explicit calls to `connector.close()` to cleanup resources.
```python
import asyncio
import asyncpg
import sqlalchemy
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from google.cloud.alloydb.connector import AsyncConnector
async def init_connection_pool(connector: AsyncConnector) -> AsyncEngine:
# initialize Connector object for connections to AlloyDB
async def getconn() -> asyncpg.Connection:
conn: asyncpg.Connection = await connector.connect(
"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>",
"asyncpg",
user="my-user",
password="my-password",
db="my-db-name"
# ... additional database driver args
)
return conn
# The AlloyDB Python Connector can be used along with SQLAlchemy using the
# 'async_creator' argument to 'create_async_engine'
pool = create_async_engine(
"postgresql+asyncpg://",
async_creator=getconn,
)
return pool
async def main():
# initialize Connector object for connections to AlloyDB
async with AsyncConnector() as connector:
# initialize connection pool
pool = await init_connection_pool(connector)
# example query
async with pool.connect() as conn:
await conn.execute(sqlalchemy.text("SELECT NOW()"))
# dispose of connection pool
await pool.dispose()
```
### Automatic IAM Database Authentication
The Python Connector supports [Automatic IAM database authentication][].
Make sure to [configure your AlloyDB Instance to allow IAM authentication][configure-iam-authn]
and [add an IAM database user][add-iam-user].
A `Connector` or `AsyncConnector` can be configured to connect to an AlloyDB instance using
automatic IAM database authentication with the `enable_iam_auth` argument set to `True`.
When configuring the `connector.connect` call for IAM authentication, the `password` field can be
omitted and the `user` field should be formatted as follows:
* 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.
For example, to connect with IAM authentication using the
`test-sa@test-project.iam.gserviceaccount.com` service account:
```python
connector.connect(
"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>",
"pg8000", # asyncpg for AsyncConnector
user="test-sa@test-project.iam",
db="my-db-name",
enable_iam_auth=True,
)
```
[Automatic IAM database authentication]: https://cloud.google.com/alloydb/docs/manage-iam-authn
[configure-iam-authn]: https://cloud.google.com/alloydb/docs/manage-iam-authn#enable
[add-iam-user]: https://cloud.google.com/alloydb/docs/manage-iam-authn#create-user
### Configuring a Lazy Refresh (Cloud Run, Cloud Functions etc.)
The Connector's `refresh_strategy` argument can be set to `"lazy"` to configure
the Python Connector to retrieve connection info lazily and as-needed.
Otherwise, a background refresh cycle runs to retrive the connection info
periodically. This setting is useful in environments where the CPU may be
throttled outside of a request context, e.g., Cloud Run, Cloud Functions, etc.
To set the refresh strategy, set the `refresh_strategy` keyword argument when
initializing a `Connector`:
```python
connector = Connector(refresh_strategy="lazy")
```
### Specifying IP Address Type
The AlloyDB Python Connector by default will attempt to establish connections
to your instance's private IP. To change this, such as connecting to AlloyDB
over a public IP address or Private Service Connect (PSC), set the `ip_type`
keyword argument when initializing a `Connector()` or when calling
`connector.connect()`.
Possible values for `ip_type` are `"PRIVATE"` (default value), `"PUBLIC"`,
and `"PSC"`.
Example:
```python
from google.cloud.alloydb.connector import Connector
import sqlalchemy
# initialize Connector object
connector = Connector()
# function to return the database connection
def getconn():
return connector.connect(
"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>",
"pg8000",
user="my-user",
password="my-password",
db="my-db-name",
ip_type="PUBLIC", # use public IP
)
# create connection pool
pool = sqlalchemy.create_engine(
"postgresql+pg8000://",
creator=getconn,
)
# use connection pool...
connector.close()
```
### Debug Logging
The AlloyDB Python Connector uses the standard [Python logging module][python-logging]
for debug logging support.
Add the below code to your application to enable debug logging with the AlloyDB
Python Connector:
```python
import logging
logging.basicConfig(format="%(asctime)s [%(levelname)s]: %(message)s")
logger = logging.getLogger(name="google.cloud.alloydb.connector")
logger.setLevel(logging.DEBUG)
```
For more details on configuring logging, please refer to the
[Python logging docs][configure-logging].
[python-logging]: https://docs.python.org/3/library/logging.html
[configure-logging]: https://docs.python.org/3/howto/logging.html#configuring-logging
## Support policy
### Major version lifecycle
This project uses [semantic versioning](https://semver.org/), and uses the
following lifecycle regarding support for a major version:
**Active** - Active versions get all new features and security fixes (that
wouldn’t otherwise introduce a breaking change). New major versions are
guaranteed to be "active" for a minimum of 1 year.
**Deprecated** - Deprecated versions continue to receive security and critical
bug fixes, but do not receive new features. Deprecated versions will be publicly
supported for 1 year.
**Unsupported** - Any major version that has been deprecated for >=1 year is
considered publicly unsupported.
## Supported Python Versions
We follow the [Python Version Support Policy][pyver] used by Google Cloud
Libraries for Python. Changes in supported Python versions will be
considered a minor change, and will be listed in the release notes.
[pyver]: https://cloud.google.com/python/docs/supported-python-versions
### Release cadence
This project aims for a minimum monthly release cadence. If no new
features or fixes have been added, a new PATCH version with the latest
dependencies is released.
### Contributing
We welcome outside contributions. Please see our
[Contributing Guide](CONTRIBUTING.md) for details on how best to contribute.
Raw data
{
"_id": null,
"home_page": "https://github.com/GoogleCloudPlatform/alloydb-python-connector",
"name": "google-cloud-alloydb-connector",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": null,
"author": "Google LLC",
"author_email": "googleapis-packages@google.com",
"download_url": "https://files.pythonhosted.org/packages/35/7a/6d5e13e193a843a71085a87a65e7e3adb485f988d8a061212abba79061e7/google_cloud_alloydb_connector-1.5.0.tar.gz",
"platform": "Posix; MacOS X; Windows",
"description": "<p align=\"center\">\n <a href=\"https://cloud.google.com/alloydb/docs/connect-language-connectors#python-pg8000\">\n <img src=\"https://raw.githubusercontent.com/GoogleCloudPlatform/alloydb-python-connector/main/docs/images/alloydb-python-connector.png\" alt=\"alloydb-python-connector image\">\n </a>\n</p>\n\n# AlloyDB Python Connector\n\n[![CI][ci-badge]][ci-build]\n[![pypi][pypi-badge]][pypi-docs]\n[![python][python-versions]][pypi-docs]\n\n[ci-badge]: https://github.com/GoogleCloudPlatform/alloydb-python-connector/actions/workflows/tests.yaml/badge.svg?event=push\n[ci-build]: https://github.com/GoogleCloudPlatform/alloydb-python-connector/actions/workflows/tests.yaml?query=event%3Apush+branch%3Amain\n[pypi-badge]: https://img.shields.io/pypi/v/google-cloud-alloydb-connector\n[pypi-docs]: https://pypi.org/project/google-cloud-alloydb-connector\n[python-versions]: https://img.shields.io/pypi/pyversions/google-cloud-alloydb-connector\n\nThe _AlloyDB Python Connector_ is an [AlloyDB](https://cloud.google.com/alloydb)\nConnector library designed for use with the Python language.\n\nUsing an AlloyDB Connector provides the following benefits:\n\n* **IAM Authorization:** uses IAM permissions to control who/what can connect to\n your AlloyDB instances\n\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\n* **Convenience:** removes the requirement to use and distribute SSL\n certificates, as well as manage firewalls or source/destination IP addresses.\n\n* (optionally) **IAM DB Authentication:** provides support for\n [AlloyDB\u2019s automatic IAM DB AuthN][iam-db-authn] feature.\n\n[iam-db-authn]: https://cloud.google.com/alloydb/docs/manage-iam-authn\n\nThe AlloyDB Python Connector is a package to be used alongside a database driver.\nCurrently supported drivers are:\n\n* [`pg8000`](https://github.com/tlocke/pg8000)\n* [`asyncpg`](https://magicstack.github.io/asyncpg)\n\n## Installation\n\nYou can install this library with `pip install`:\n\n### pg8000\n\n```sh\npip install \"google-cloud-alloydb-connector[pg8000]\"\n```\n\nSee [Synchronous Driver Usage](#synchronous-driver-usage) for details.\n\n### asyncpg\n\n```sh\npip install \"google-cloud-alloydb-connector[asyncpg]\"\n```\n\nSee [Async Driver Usage](#async-driver-usage) for details.\n\n### APIs and Services\n\nThis package requires the following to connect successfully:\n\n* IAM principal (user, service account, etc.) with the [AlloyDB\n Client][client-role] role or equivalent. [Credentials](#credentials)\n for the IAM principal are used to authorize connections to an AlloyDB instance.\n\n* The [AlloyDB API][alloydb-api] to be enabled within your Google Cloud\n Project. By default, the API will be called in the project associated with the\n IAM principal.\n\n[alloydb-api]: https://console.cloud.google.com/apis/api/alloydb.googleapis.com\n[client-role]: https://cloud.google.com/alloydb/docs/auth-proxy/overview#how-authorized\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\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 AlloyDB instance.\n\nAlloyDB supports network connectivity through public IP addresses and private,\ninternal IP addresses, as well as [Private Service Connect][psc] (PSC). \nBy default this package will attempt to connect over a\nprivate IP connection. When doing so, this package must be run in an\nenvironment that is connected to the [VPC Network][vpc] that hosts your\nAlloyDB private IP address.\n\nPlease see [Configuring AlloyDB Connectivity][alloydb-connectivity] for more details.\n\n[vpc]: https://cloud.google.com/vpc/docs/vpc\n[alloydb-connectivity]: https://cloud.google.com/alloydb/docs/configure-connectivity\n[psc]: https://cloud.google.com/vpc/docs/private-service-connect\n\n### Synchronous Driver Usage\n\nTo connect to AlloyDB using the connector, inititalize a `Connector`\nobject and call it's `connect` method with the proper input parameters.\n\nThe `Connector` itself creates database connection objects by calling its `connect` method\nbut does not manage database connection pooling. For this reason, it is recommended to use\nthe connector alongside a library that can create connection pools, such as\n[SQLAlchemy](https://www.sqlalchemy.org/). This will allow for connections to remain open and\n be reused, reducing connection overhead and the number of connections needed.\n\nIn the Connector's `connect` method below, input your AlloyDB instance URI as\nthe first positional argument and the name of the database driver for the\nsecond positional argument. Insert the rest of your connection keyword arguments\nlike `user`, `password` and `db` etc.\n\nTo use this connector with SQLAlchemy, use the `creator` argument for `sqlalchemy.create_engine`:\n\n```python\nfrom google.cloud.alloydb.connector import Connector\nimport sqlalchemy\n\n# initialize Connector object\nconnector = Connector()\n\n# function to return the database connection\ndef getconn():\n conn = connector.connect(\n \"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>\",\n \"pg8000\",\n user=\"my-user\",\n password=\"my-password\",\n db=\"my-db-name\"\n # NOTE: this assumes private IP by default.\n # Add the following keyword arg to use public IP:\n # ip_type=\"PUBLIC\"\n )\n return conn\n\n# create connection pool\npool = sqlalchemy.create_engine(\n \"postgresql+pg8000://\",\n creator=getconn,\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 it's `close()` method as follows:\n\n```python\nconnector.close()\n```\n\n### Synchronous 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.alloydb.connector import Connector\nimport sqlalchemy\n\n# helper function to return SQLAlchemy connection pool\ndef init_connection_pool(connector: Connector) -> sqlalchemy.engine.Engine:\n # function used to generate database connection\n def getconn():\n conn = connector.connect(\n \"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>\",\n \"pg8000\",\n user=\"my-user\",\n password=\"my-password\",\n db=\"my-db-name\"\n )\n return conn\n\n # create connection pool\n pool = sqlalchemy.create_engine(\n \"postgresql+pg8000://\",\n creator=getconn,\n )\n return pool\n\n# initialize Connector as context manager\nwith Connector() as connector:\n # initialize connection pool\n pool = init_connection_pool(connector)\n # insert statement\n insert_stmt = sqlalchemy.text(\n \"INSERT INTO my_table (id, title) VALUES (:id, :title)\",\n )\n \n # interact with AlloyDB 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### Async Driver Usage\n\nThe AlloyDB Connector is compatible with [asyncio][] to improve the speed and\nefficiency of database connections through concurrency. The `AsyncConnector`\ncurrently supports the following asyncio database drivers:\n\n- [asyncpg](https://magicstack.github.io/asyncpg)\n\n[asyncio]: https://docs.python.org/3/library/asyncio.html\n\n```python\nimport asyncpg\n\nimport sqlalchemy\nfrom sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine\n\nfrom google.cloud.alloydb.connector import AsyncConnector\n\nasync def init_connection_pool(connector: AsyncConnector) -> AsyncEngine:\n # initialize Connector object for connections to AlloyDB\n async def getconn() -> asyncpg.Connection:\n conn: asyncpg.Connection = await connector.connect(\n \"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>\",\n \"asyncpg\",\n user=\"my-user\",\n password=\"my-password\",\n db=\"my-db-name\"\n # NOTE: this assumes private IP by default.\n # Add the following keyword arg to use public IP:\n # ip_type=\"PUBLIC\"\n # ... additional database driver args\n )\n return conn\n\n # The AlloyDB 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=getconn,\n )\n return pool\n\nasync def main():\n connector = AsyncConnector()\n\n # initialize connection pool\n pool = await init_connection_pool(connector)\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 # close Connector\n await connector.close()\n\n```\n\nFor more details on additional arguments with an `asyncpg.Connection`, please\nvisit the [official documentation][asyncpg-docs].\n\n[asyncpg-docs]: https://magicstack.github.io/asyncpg/current/api/index.html\n\n### Async Context Manager\n\nThe `AsyncConnector` also may be used as an async context manager, removing the\nneed for explicit calls to `connector.close()` to cleanup resources.\n\n```python\nimport asyncio\nimport asyncpg\n\nimport sqlalchemy\nfrom sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine\n\nfrom google.cloud.alloydb.connector import AsyncConnector\n\nasync def init_connection_pool(connector: AsyncConnector) -> AsyncEngine:\n # initialize Connector object for connections to AlloyDB\n async def getconn() -> asyncpg.Connection:\n conn: asyncpg.Connection = await connector.connect(\n \"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>\",\n \"asyncpg\",\n user=\"my-user\",\n password=\"my-password\",\n db=\"my-db-name\"\n # ... additional database driver args\n )\n return conn\n\n # The AlloyDB 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=getconn,\n )\n return pool\n\nasync def main():\n # initialize Connector object for connections to AlloyDB\n async with AsyncConnector() as connector:\n # initialize connection pool\n pool = await init_connection_pool(connector)\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### Automatic IAM Database Authentication\n\nThe Python Connector supports [Automatic IAM database authentication][].\n\nMake sure to [configure your AlloyDB Instance to allow IAM authentication][configure-iam-authn]\nand [add an IAM database user][add-iam-user].\n\nA `Connector` or `AsyncConnector` can be configured to connect to an AlloyDB instance using\nautomatic IAM database authentication with the `enable_iam_auth` argument set to `True`.\n\nWhen configuring the `connector.connect` call for IAM authentication, the `password` field can be\nomitted and the `user` field should be formatted as follows:\n\n* For an IAM user account, this is the user's email address.\n* For a service account, it is the service account's email without the\n`.gserviceaccount.com` domain suffix.\n\nFor example, to connect with IAM authentication using the\n`test-sa@test-project.iam.gserviceaccount.com` service account:\n\n```python\nconnector.connect(\n \"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>\",\n \"pg8000\", # asyncpg for AsyncConnector\n user=\"test-sa@test-project.iam\",\n db=\"my-db-name\",\n enable_iam_auth=True,\n)\n```\n\n[Automatic IAM database authentication]: https://cloud.google.com/alloydb/docs/manage-iam-authn\n[configure-iam-authn]: https://cloud.google.com/alloydb/docs/manage-iam-authn#enable\n[add-iam-user]: https://cloud.google.com/alloydb/docs/manage-iam-authn#create-user\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 AlloyDB Python Connector by default will attempt to establish connections\nto your instance's private IP. To change this, such as connecting to AlloyDB\nover a public IP address or Private Service Connect (PSC), set the `ip_type`\nkeyword argument when initializing a `Connector()` or when calling\n`connector.connect()`.\n\nPossible values for `ip_type` are `\"PRIVATE\"` (default value), `\"PUBLIC\"`,\nand `\"PSC\"`.\n\nExample:\n\n```python\nfrom google.cloud.alloydb.connector import Connector\n\nimport sqlalchemy\n\n# initialize Connector object\nconnector = Connector()\n\n# function to return the database connection\ndef getconn():\n return connector.connect(\n \"projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>\",\n \"pg8000\",\n user=\"my-user\",\n password=\"my-password\",\n db=\"my-db-name\",\n ip_type=\"PUBLIC\", # use public IP\n )\n\n# create connection pool\npool = sqlalchemy.create_engine(\n \"postgresql+pg8000://\",\n creator=getconn,\n)\n\n# use connection pool...\nconnector.close()\n```\n\n### Debug Logging\n\nThe AlloyDB 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 AlloyDB\nPython Connector:\n\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(asctime)s [%(levelname)s]: %(message)s\")\nlogger = logging.getLogger(name=\"google.cloud.alloydb.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\u2019t 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 >=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\n\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",
"bugtrack_url": null,
"license": "Apache 2.0",
"summary": "A Python client library for connecting securely to your Google Cloud AlloyDB instances.",
"version": "1.5.0",
"project_urls": {
"Homepage": "https://github.com/GoogleCloudPlatform/alloydb-python-connector"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "d5f1ce2a384e2540e2aed8af77fbcf2fddf49ff38a5f2d7bd5e76fa93272babd",
"md5": "27ec427a718252f8d2b3294ec389bf95",
"sha256": "201ea1ae83ad575733af901d784ee3708c5fab18cbb58ba55f2d1c32bc7d3ae1"
},
"downloads": -1,
"filename": "google_cloud_alloydb_connector-1.5.0-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "27ec427a718252f8d2b3294ec389bf95",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": ">=3.9",
"size": 42117,
"upload_time": "2024-11-13T18:09:48",
"upload_time_iso_8601": "2024-11-13T18:09:48.742634Z",
"url": "https://files.pythonhosted.org/packages/d5/f1/ce2a384e2540e2aed8af77fbcf2fddf49ff38a5f2d7bd5e76fa93272babd/google_cloud_alloydb_connector-1.5.0-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "357a6d5e13e193a843a71085a87a65e7e3adb485f988d8a061212abba79061e7",
"md5": "1a6e5af9ad8d947ea9fefc5cb51f1507",
"sha256": "30cc09ef4d1a4c07643ad768227f50adb4504dafe9fddb26c2b49b604913cba4"
},
"downloads": -1,
"filename": "google_cloud_alloydb_connector-1.5.0.tar.gz",
"has_sig": false,
"md5_digest": "1a6e5af9ad8d947ea9fefc5cb51f1507",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 32946,
"upload_time": "2024-11-13T18:09:50",
"upload_time_iso_8601": "2024-11-13T18:09:50.595522Z",
"url": "https://files.pythonhosted.org/packages/35/7a/6d5e13e193a843a71085a87a65e7e3adb485f988d8a061212abba79061e7/google_cloud_alloydb_connector-1.5.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-13 18:09:50",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "GoogleCloudPlatform",
"github_project": "alloydb-python-connector",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "aiofiles",
"specs": [
[
"==",
"24.1.0"
]
]
},
{
"name": "aiohttp",
"specs": [
[
"==",
"3.10.10"
]
]
},
{
"name": "cryptography",
"specs": [
[
"==",
"43.0.3"
]
]
},
{
"name": "google-auth",
"specs": [
[
"==",
"2.36.0"
]
]
},
{
"name": "requests",
"specs": [
[
"==",
"2.32.3"
]
]
},
{
"name": "protobuf",
"specs": [
[
"==",
"4.25.5"
]
]
}
],
"lcname": "google-cloud-alloydb-connector"
}