【问题标题】:Connecting to Google Cloud SQL Postgres instance using psycopg2使用 psycopg2 连接到 Google Cloud SQL Postgres 实例
【发布时间】:2021-04-09 23:04:08
【问题描述】:

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

我现在创建了一个 postgreSQL 实例并使用默认数据库 postgres。 我能够从 pgadmin 工具以及 gcloud shell 进行连接,并且查询给出了预期的结果。

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

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

当我运行它时,get 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


    【解决方案1】:

    正如this article 中提到的从应用引擎连接到 Cloud SQL:

    Connecting with Unix sockets
    
    Once correctly configured, you can connect your service to your Cloud SQL instance's Unix domain socket accessed on the environment's filesystem at the following path: /cloudsql/INSTANCE_CONNECTION_NAME.
    
    The INSTANCE_CONNECTION_NAME can be found on the Overview page for your instance in the Google Cloud Console or by running the following command:
     
        gcloud sql instances describe [INSTANCE_NAME]
    

    【讨论】:

    • 我使用的是 psycopg2 模块,而不是 sqlalchemy ORM。你能帮我处理 psycopg2 模块吗?
    • 无论您使用 sqlalchemy 还是 psycopg2,UNIX 套接字路径都是相同的。
    • 发布了我的解决方案作为答案
    【解决方案2】:

    确保在您的烧瓶服务器上安装 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,它有一个端口被转发以访问我的烧瓶服务器。我不确定您访问主机的方式。我的烧瓶 API 和数据库实际上托管在谷歌云中不同的虚拟机上。我希望这有帮助,如果不能提供更多的上下文,我可以多看一下。

    【讨论】:

      【解决方案3】:
      unix_socket = '/cloudsql/{}'.format("my-project-id:us-central1:my-db-name")
      
      conn = psycopg2.connect(database="postgres", user = "postgres", password = "password", host = unix_socket)
      

      这对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        • 2023-02-07
        • 2020-06-07
        • 2021-12-25
        • 1970-01-01
        • 2020-05-23
        • 2019-10-28
        相关资源
        最近更新 更多