Skip to content

Instantly share code, notes, and snippets.

@jackwotherspoon
Last active February 14, 2023 18:35
Show Gist options
  • Save jackwotherspoon/46c30043f5875869995e40da94009f91 to your computer and use it in GitHub Desktop.
Save jackwotherspoon/46c30043f5875869995e40da94009f91 to your computer and use it in GitHub Desktop.
from google.cloud.sql.connector import Connector
import sqlalchemy
# wrap engine creation so arguments are dynamically passed
def init_connection_engine(connector: Connector, instance_connection_name: str, user: str, password: str):
def getconn():
connection = connector.connect(
instance_connection_name,
"pg8000",
user=user,
password=password,
db="YOUR_DB",
)
return connection
engine = sqlalchemy.create_engine(
"postgresql+pg8000://",
creator=getconn,
)
engine.dialect.description_encoding = None
return engine
# your application code
def db_connect():
with Connector() as connector:
pool = init_connection_engine(connector, "project:region:instance1", "user1", "pass1")
pool2 = init_connection_engine(connector, "project:region:instance1", "user2", "pass2")
# ... connect to pools
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment