使用 psycopg2 连接到 Google Cloud SQL Postgres 实例

问题描述 投票:0回答:4

我正在尝试使用 psycopg2 连接到 Google Cloud SQL Postgres。

我现在已经创建了一个 postgreSQL 实例并使用默认数据库

postgres
。 我可以从 pgadmin 工具以及 gcloud shell 进行连接,并且查询给出了预期的结果。

我开发了一个 Flask 应用程序并部署在标准应用程序引擎上。

conn = psycopg2.connect(database="postgres", user = "postgres", password = "password", host = "/cloudsql/my-new-db")

当我运行它时,出现

psycopg2.OperationalError: could not connect to server: No such file or directory
错误。

我有预感主机值不正确。我尝试了各种选项,例如

/cloudsql/<prj-name>.<region>.<db-instance-name>

但是,似乎没有任何效果。我还应该做什么来消除这个错误?

postgresql google-app-engine flask psycopg2 google-cloud-sql
4个回答
2
投票
unix_socket = '/cloudsql/{}'.format("my-project-id:us-central1:my-db-name")

conn = psycopg2.connect(database="postgres", user = "postgres", password = "password", host = unix_socket)

这对我有用。


1
投票

本文中所述,关于从应用程序引擎连接到 Cloud SQL:

与 Unix 套接字连接

正确配置后,您可以将服务连接到在环境文件系统上访问的 Cloud SQL 实例的 Unix 域套接字,路径为:/cloudsql/INSTANCE_CONNECTION_NAME。

INSTANCE_CONNECTION_NAME 可以在 Google Cloud Console 中实例的概述页面上找到,也可以通过运行以下命令找到:

    gcloud sql instances describe [INSTANCE_NAME]

编辑:格式化


1
投票

在您的 Flask 服务器上,确保安装 psycopg2 库(pip install 或使用 apt-get install)。我附上了一小段代码,用于成功连接到我的 Postgres 数据库,也许它会以某种方式提供帮助。我注意到您没有指定端口。

connection = psycopg2.connect(
   user = 'userName',
   password = password,
   host = 'some ip here',
   port = '5432',
   database = 'db name here'
)

我的例子中的主机是服务器的IP,它有一个转发的端口用于访问我的flask服务器。我不确定您访问主机的方式。我的 Flask API 和 DB 实际上托管在谷歌云内的单独虚拟机上。我希望这对您有所帮助,如果没有帮助,也许可以提供更多背景信息,我可以更多地查看它。


0
投票

在您的谷歌云上只需搜索 SQL,然后复制数据库的实例连接名称。 在您的烧瓶应用程序中只需替换

conn = psycopg2.connect(database="postgres", user = "postgres", password = "password", host = "/cloudsql/my-new-db")

conn = psycopg2.connect(database="postgres", user = "postgres", password = "password", host = "/cloudsql/your-instance-connection-name")
© www.soinside.com 2019 - 2024. All rights reserved.