Package: google-cloud-alloydb-connector
AlloyDB Python ConnectorTheAlloyDB Python Connectoris anAlloyDBConnector 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 instancesImproved 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 forAlloyDB’s automatic IAM DB AuthNfeature.The AlloyDB Python Connector is a package to be used alongside a database driver.
Currently supported drivers are:pg8000asyncpgInstallationYou can install this library withpip install:pg8000pipinstall"google-cloud-alloydb-connector[pg8000]"SeeSynchronous Driver Usagefor details.asyncpgpipinstall"google-cloud-alloydb-connector[asyncpg]"SeeAsync Driver Usagefor details.APIs and ServicesThis package requires the following to connect successfully:IAM principal (user, service account, etc.) with theAlloyDB
Clientrole or equivalent.Credentialsfor the IAM principal are used to authorize connections to an AlloyDB instance.TheAlloyDB Admin APIto be enabled within your Google Cloud
Project. By default, the API will be called in the project associated with the
IAM principal.CredentialsThis library uses theApplication Default Credentials (ADC)strategy for
resolving credentials. Please seethese instructions for how to set your ADC(Google Cloud Application vs Local Development, IAM user vs service account credentials),
or consult thegoogle.authpackage.UsageThis 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. 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 theVPC Networkthat hosts your
AlloyDB private IP address.Please seeConfiguring AlloyDB Connectivityfor more details.Synchronous Driver UsageTo connect to AlloyDB using the connector, inititalize aConnectorobject and call it'sconnectmethod with the proper input parameters.TheConnectoritself creates database connection objects by calling itsconnectmethod
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 asSQLAlchemy. This will allow for connections to remain open and
be reused, reducing connection overhead and the number of connections needed.In the Connector'sconnectmethod 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
likeuser,passwordanddbetc.To use this connector with SQLAlchemy, use thecreatorargument forsqlalchemy.create_engine:fromgoogle.cloud.alloydb.connectorimportConnectorimportsqlalchemy# initialize Connector objectconnector=Connector()# function to return the database connectiondefgetconn():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")returnconn# create connection poolpool=sqlalchemy.create_engine("postgresql+pg8000://",creator=getconn,)The returned connection pool engine can then be used to query and modify the database.# insert statementinsert_stmt=sqlalchemy.text("INSERT INTO my_table (id, title) VALUES (:id, :title)",)withpool.connect()asdb_conn:# insert into databasedb_conn.execute(insert_stmt,parameters={"id":"book1","title":"Book One"})# query databaseresult=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 resultsforrowinresult:print(row)To close theConnectorobject's background resources, call it'sclose()method as follows:connector.close()Synchronous Context ManagerTheConnectorobject can also be used as a context manager in order to
automatically close and cleanup resources, removing the need for explicit
calls toconnector.close().Connector as a context manager:fromgoogle.cloud.alloydb.connectorimportConnectorimportsqlalchemy# build connectiondefgetconn():withConnector()asconnector: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")returnconn# create connection poolpool=sqlalchemy.create_engine("postgresql+pg8000://",creator=getconn,)# insert statementinsert_stmt=sqlalchemy.text("INSERT INTO my_table (id, title) VALUES (:id, :title)",)# interact with AlloyDB database using connection poolwithpool.connect()asdb_conn:# insert into databasedb_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 databaseresult=db_conn.execute(sqlalchemy.text("SELECT * from my_table")).fetchall()# Do something with the resultsforrowinresult:print(row)Async Driver UsageThe AlloyDB Connector is compatible withasyncioto improve the speed and
efficiency of database connections through concurrency. TheAsyncConnectorcurrently supports the following asyncio database drivers:asyncpgimportasyncpgimportsqlalchemyfromsqlalchemy.ext.asyncioimportAsyncEngine,create_async_enginefromgoogle.cloud.alloydb.connectorimportAsyncConnectorasyncdefinit_connection_pool(connector:AsyncConnector)->AsyncEngine:# initialize Connector object for connections to AlloyDBasyncdefgetconn()->asyncpg.Connection:conn:asyncpg.Connection=awaitconnector.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)returnconn# 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,)returnpoolasyncdefmain():connector=AsyncConnector()# initialize connection poolpool=awaitinit_connection_pool(connector)# example queryasyncwithpool.connect()asconn:awaitconn.execute(sqlalchemy.text("SELECT NOW()"))# dispose of connection poolawaitpool.dispose()# close Connectorawaitconnector.close()For more details on additional arguments with anasyncpg.Connection, please
visit theofficial documentation.Async Context ManagerTheAsyncConnectoralso may be used as an async context manager, removing the
need for explicit calls toconnector.close()to cleanup resources.importasyncioimportasyncpgimportsqlalchemyfromsqlalchemy.ext.asyncioimportAsyncEngine,create_async_enginefromgoogle.cloud.alloydb.connectorimportAsyncConnectorasyncdefinit_connection_pool(connector:AsyncConnector)->AsyncEngine:# initialize Connector object for connections to AlloyDBasyncdefgetconn()->asyncpg.Connection:conn:asyncpg.Connection=awaitconnector.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)returnconn# 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,)returnpoolasyncdefmain():# initialize Connector object for connections to AlloyDBasyncwithAsyncConnector()asconnector:# initialize connection poolpool=awaitinit_connection_pool(connector)# example queryasyncwithpool.connect()asconn:awaitconn.execute(sqlalchemy.text("SELECT NOW()"))# dispose of connection poolawaitpool.dispose()Automatic IAM Database AuthenticationThe Python Connector supportsAutomatic IAM database authentication.Make sure toconfigure your AlloyDB Instance to allow IAM authenticationandadd an IAM database user.AConnectororAsyncConnectorcan be configured to connect to an AlloyDB instance using
automatic IAM database authentication with theenable_iam_authargument set toTrue.When configuring theconnector.connectcall for IAM authentication, thepasswordfield can be
omitted and theuserfield 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.comdomain suffix.For example, to connect with IAM authentication using thetest-sa@test-project.iam.gserviceaccount.comservice account:connector.connect("projects/<YOUR_PROJECT>/locations/<YOUR_REGION>/clusters/<YOUR_CLUSTER>/instances/<YOUR_INSTANCE>","pg8000",# asyncpg for AsyncConnectoruser="test-sa@test-project.iam",db="my-db-name",enable_iam_auth=True,)Specifying IP Address TypeThe 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, set theip_typekeyword argument when initializing
aConnector()or when callingconnector.connect().Possible values forip_typeareIPTypes.PRIVATE(default value), andIPTypes.PUBLIC.
Example:fromgoogle.cloud.alloydb.connectorimportConnector,IPTypesimportsqlalchemy# initialize Connector objectconnector=Connector()# function to return the database connectiondefgetconn():returnconnector.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=IPTypes.PUBLIC,# use public IP)# create connection poolpool=sqlalchemy.create_engine("postgresql+pg8000://",creator=getconn,)# use connection pool...connector.close()Support policyMajor version lifecycleThis project usessemantic versioning, 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 VersionsWe follow thePython Version Support Policyused 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.Release cadenceThis 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.ContributingWe welcome outside contributions. Please see ourContributing Guidefor details on how best to contribute.