使用 Python 和 SQLAlchemy 从 Google Cloud Function 连接到 Cloud SQL

Connecting to Cloud SQL from Google Cloud Function using Python and SQLAlchemy

我读完了 documentation related to connecting to MysQL hosted in Cloud SQL from GCF and still can't connect. Also, tried all hints in documentation of SQLAlchemy related to this。 我正在使用以下连接

con = 'mysql+pymysql://USER:PASSWORD@/MY_DB?unix_socket=/cloudsql/Proj_ID:Zone:MySQL_Instance_ID'
mysqlEngine = sqlalchemy.create_engine(con)

我得到的错误是:

(pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") (Background on this error at: http://sqlalche.me/e/e3q8)

我认为您的问题出在 con 字符串变量末尾的 <PROJECT_ID>:<REGION>:<INSTANCE_ID> 表示的 Connection_name 上。

顺便引用一下:

con = 'mysql+pymysql://USER:PASSWORD@/MY_DB?unix_socket=/cloudsql/<PROJECT_ID>:<REGION>:<INSTANCE_ID>'

用这个命令检查你是否写对了:

gcloud sql instances describe <INSTANCE_ID> | grep connectionName

如果不是这种情况,请记住 these considerations present in the Cloud Functions official documentation:

First Generation MySQL instances must be in the same region as your Cloud Function. Second Generation MySQL instances as well as PostgreSQL instances work with Cloud Functions in any region.

Your Cloud Function has access to all Cloud SQL instances in your project. You can access Second Generation MySQL instances as well as PostgreSQL instances in other projects if your Cloud Function's service account (listed on the Cloud Function's General tab in the GCP Console) is added as a member in IAM on the project with the Cloud SQL instance(s) with the Cloud SQL Client role.

您需要确保使用正确的 /cloudsql/<INSTANCE_CONNECTION_NAME>(格式为 <PROJECT_ID>:<REGION>:<INSTANCE_ID>)。如果您的 Cloud SQL 实例与您的 Function 在同一个项目和区域中,这应该是所有需要的。

GCF 文档还强烈建议将池限制为单个连接。这意味着您应该在引擎设置中同时设置 pool_size=1max_overflow=0

如果您想查看如何设置这些设置的示例,请查看 Github 上的示例应用程序。

经过与 Google 支持的长期讨论后,我们发现原因是:我们应该在没有任何防火墙规则的情况下启用 public 对云 SQL 的访问。它没有记录,可能会让你发疯,但支持团队的灵丹妙药是:它处于测试阶段!

我遇到了这个问题。服务帐户是正确的,具有正确的权限,与我的 App Engine 应用程序中的连接字符串完全相同。仍然在日志中得到这个。

dial unix /cloudsql/project:region:instance connect: no such file or directory

从第 2 代 Cloud Function 切换到第 1 代解决了这个问题。没有看到它记录在任何地方 2nd 无法连接到云 SQL 个实例。