我尝试使用google.cloud.sql.connector
连接到cloudsql服务器,下面的代码摘自文档:
def connect_with_connector(self) -> sqlalchemy.engine.base.Engine:
"""
Initializes a connection pool for a Cloud SQL instance of Postgres.
Uses the Cloud SQL Python Connector package.
"""
# Note: Saving credentials in environment variables is convenient, but not
# secure - consider a more secure solution such as
# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help
# keep secrets safe.
instance_connection_name = os.environ[self.keys["gProj"]]
# e.g. 'project:region:instance'
db_user = os.environ[self.keys["gUser"]] # e.g. 'my-db-user'
db_pass = os.environ[self.keys["gPass"]] # e.g. 'my-db-password'
db_name = os.environ[self.keys["gDB"]] # e.g. 'my-database'
ip_type = IPTypes.PRIVATE if os.environ.get(self.keys["gPrivIP"]) else IPTypes.PUBLIC
# initialize Cloud SQL Python Connector object
connector = Connector()
def getconn() -> pg8000.dbapi.Connection:
conn: pg8000.dbapi.Connection = connector.connect(
instance_connection_name,
"pg8000",
user=db_user,
password=db_pass,
db=db_name,
ip_type=ip_type,
)
return conn
# The Cloud SQL Python Connector can be used with SQLAlchemy
# using the 'creator' argument to 'create_engine'
pool = sqlalchemy.create_engine(
"postgresql+pg8000://",
creator=getconn,
# ...
)
return pool
字符串
我给予它的连接名为instance_connection_name
,但它给我这个错误:
instance_connection_name = os.environ[self.keys["gProj"]]
File "C:\Users\--\AppData\Local\Programs\Python\Python310\lib\os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: '--connection_name_here--'
型
我已经仔细检查了连接名称是正确的,我已经弄乱了IP地址,有人知道问题可能是什么吗?
1条答案
按热度按时间0pizxfdo1#
我意识到这是
os.environ
的一个问题,我不知道为什么示例使用它,但我只是直接将参数传递给连接器,它工作得很好。字符串