第二代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
相关产品推荐
相关产品推荐

