Dav*_*res 0 python postgresql connector google-cloud-sql pg8000
我正在尝试使用本地计算机(本地)中的 Python 代码并使用我的云 sql 实例的私有 IP 连接到云 sql postgreSQL 实例。
from google.cloud.sql.connector import Connector, IPTypes
import pg8000
import sqlalchemy
from sqlalchemy import text
def connect_with_connector_auto_iam_authn():
instance_connection_name = "connection name"
db_user = "SA name" # e.g. 'my-db-user'
db_name = "postgres" # e.g. 'my-database'
ip_type = IPTypes.PRIVATE
# 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=db_name,
enable_iam_auth=True,
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, pool_pre_ping=True
)
with pool.connect() as conn:
results = conn.execute(text("SELECT current_user, current_database();"))
for row in results:
print(row)
print("connected")
return "connected"
connect_with_connector_auto_iam_authn()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:
TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确响应而导致连接尝试失败,或者由于连接的主机未能响应而建立连接失败上述异常是导致以下异常的直接原因:
sqlalchemy.exc.InterfaceError: (pg8000.exceptions.InterfaceError) 无法创建到主机 10.82.1.2 和端口 3307 的连接(超时为 None,source_address 为 None)。
我想也许我无法使用我的机器上的私有IP,而使用私有IP的唯一方法是在同一个VPC内,这意味着使用另一个GCP资源。
提前致谢!
您可以使用 SSH 反向隧道从 Google Cloud 外部连接到配置有私有 IP 地址的 Cloud SQL。这确实需要 Compute Engine 实例提供 SSH 隧道。
| 归档时间: |
|
| 查看次数: |
189 次 |
| 最近记录: |