如何从 Cloud Functions 连接到 Google Cloud PostgreSQL 数据库?

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

我正在遵循 使用 Cloud Functions 连接到 Cloud SQL 教程,但我的 Cloud Function 无法连接到 PostgreSQL 数据库

这是我的功能代码:

import sqlalchemy

connection_name = "redacted-1234a:asia-northeast3:myinstance2"

query_string =  dict({"unix_sock": "/cloudsql/{}/.s.PGSQL.5432".format(connection_name)})

def insert(request):
    print(f"Started function - query_string: {query_string}")
    request_json = request.get_json()
    stmt = sqlalchemy.text('insert into {} ({}) values ({})'.format("entries", "(guestName, content)", "(\"cloud hello\", \"Got here!\")"))
    
    db = sqlalchemy.create_engine(
      sqlalchemy.engine.url.URL(
        drivername="postgres+pg8000",
        username="postgres",
        password=redacted,
        database="guestbook",
        query=query_string,
      ),
      pool_size=5,
      max_overflow=2,
      pool_timeout=30,
      pool_recycle=1800
    )
    print("Created engine")
    try:
        with db.connect() as conn:
            print("Connected to engine")
            conn.execute(stmt)
    except Exception as e:
        return 'Error: {}'.format(str(e))
    return 'ok'

当我从“测试”选项卡运行它时,我得到:

2023-12-20 10:58:06.728 JST - Started function - query_string: {'unix_sock': '/cloudsql/nownow-8907a:asia-northeast3:myinstance2/.s.PGSQL.5432'}
2023-12-20 10:58:09.054 JST - Created engine
Error: (pg8000.core.InterfaceError) ('communication error', FileNotFoundError(2, 'No such file or directory'))
(Background on this error at: http://sqlalche.me/e/rvf5)

以下是我在设置数据库时在 Cloud Shell 中运行的内容:

$ gcloud sql connect myinstance2 --user=postgres
Allowlisting your IP for incoming connection for 5 minutes...done.                                                                                                                                      
Connecting to database with SQL user [postgres].Password: # typed in redacted
psql (16.1 (Debian 16.1-1.pgdg110+1), server 15.4)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.
postgres=> CREATE DATABASE guestbook;
\CREATE DATABASE
postgres=> \connect guestbook;
Password: # typed in redacted
psql (16.1 (Debian 16.1-1.pgdg110+1), server 15.4)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
You are now connected to database "guestbook" as user "postgres".
guestbook=> CREATE TABLE entries (guestName VARCHAR(255), content VARCHAR(255), entryID SERIAL PRIMARY KEY);
CREATE TABLE

我怎样才能让它发挥作用?我觉得我已经检查了一切:

  • 该函数使用具有 Cloud SQL 客户端角色的服务账户运行
  • redacted 是 postgres 本身和数据库的密码(我可以通过 Cloud Shell 使用它进行连接)
  • PostgreSQL 实例同时具有公共 IP 和私有 IP,并启用了“私有路径”
  • SQL > 连接 > 安全性将 Google Cloud 服务授权和 App Engine 授权设置为“已启用”,并将“仅允许 SSL 连接”和“需要受信任的客户端证书”设置为“已禁用”

云函数的另一个有趣的异常现象是,我在创建过程中验证了 3 次,选择了“允许未经身份验证的调用”,但在创建函数后,它又回到了“需要身份验证”。不过,我认为这不是超级相关,因为我仍然能够运行该函数,我只是无法连接到数据库。

python postgresql google-cloud-platform google-cloud-functions google-cloud-sql
1个回答
0
投票

奇怪的是,它不是我遵循的协作的一部分,但您还需要在此处执行以下步骤:https://cloud.google.com/sql/docs/mysql/connect-functions#configure

您需要仔细关注该页面(以防它发生变化),但一般步骤是:

  • 进入云跑页面
  • 转到,然后编辑您的函数
  • 在“容器”选项卡中,找到您的连接名称并将其添加到 Cloud SQL 连接

部署这些更改后,您的函数现在将能够连接到 SQL 数据库

© www.soinside.com 2019 - 2024. All rights reserved.