Last active
February 14, 2023 18:35
-
-
Save jackwotherspoon/46c30043f5875869995e40da94009f91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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