You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

第二代Google Cloud Function数据库访问时超时求助

第二代Google Cloud Function调用PostgreSQL时卡在session.execute()超时

我用Python编写了一个第二代Google Cloud Function,功能是从外部API拉取数据并写入Google Cloud SQL托管的PostgreSQL数据库。运行该函数时出现超时问题,数据库未发生任何变更。通过添加print语句排查发现,sqlalchemy的engine创建正常,但程序卡在第一个session.execute(stmt)步骤无法继续。不过本地使用function-framework连接云数据库运行该函数时完全正常。我采用Python的cloud.sql.connector库(搭配pg8000驱动)连接数据库。

已尝试的排查操作

  • 给函数分配拥有全局Owner角色的服务账号
  • 确认数据库凭据在本地及另一个云函数中均可正常使用
  • 分别通过Cloud Shell命令 curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" https://FUNCTION_URL 和本地命令 gcloud function call 调用函数,结果均一致
  • 对比同一项目、同一区域、同一数据库实例的另一个云函数,唯一差异在于本函数是第二代Cloud Function,且使用connector库而非Unix套接字连接数据库,两者使用同一GCP服务账号、同一SQL登录信息

相关代码片段

创建engine的代码

connector = Connector()

def getconn() -> pg8000.dbapi.Connection:
    conn: pg8000.dbapi.Connection = connector.connect(
        instance_connection_name,
        "pg8000",
        user=username,
        password=password,
        db=database,
        ip_type=IPTypes.PUBLIC,
    )
    return conn
print("creating db connection...")
# create a connection to the database
engine = create_engine("postgresql+pg8000://",
                       creator=getconn,
                       echo=False)
Session = sessionmaker(bind=engine)
session = Session()
print("db con ok")

无法完成执行的方法(从未打印"ok")

def wipe_table(name):
    print(f"Wiping staging table {name}...")
    stmt = text(f"TRUNCATE {name};")
    session.execute(stmt)
    print("ok")

内容的提问来源于stack exchange,提问作者Tenocticatl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:02:42