Google Cloud Function with Cloud MySQL 授权失败([Errno 111] 连接被拒绝)

Google Cloud Function with Cloud MySQL Authorisation fails ([Errno 111] Connection refused)

我正在尝试通过 Google 云函数连接到我的 Google 云 MySQL 数据库以读取一些数据。函数构建成功,但执行时只显示:

Error: (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)

这是我的连接代码:

import sqlalchemy

# Depending on which database you are using, you'll set some variables differently. 
# In this code we are inserting only one field with one value. 
# Feel free to change the insert statement as needed for your own table's requirements.

# Uncomment and set the following variables depending on your specific instance and database:
connection_name = "single-router-309308:europe-west4:supermarkt-database"
db_name = "supermarkt-database"
db_user = "hidden"
db_password = "hidden"

# If your database is MySQL, uncomment the following two lines:
driver_name = 'mysql+pymysql'
query_string = dict({"unix_socket": "/cloudsql/{}".format(connection_name)})

# If the type of your table_field value is a string, surround it with double quotes. < SO note: I didn't really understand this line. Is this the problem?

def insert(request):
    request_json = request.get_json()
    stmt = sqlalchemy.text('INSERT INTO products VALUES ("Testid", "testname", "storename", "testbrand", "4.20", "1kg", "super lekker super mooi", "none")')
    
    db = sqlalchemy.create_engine(
      sqlalchemy.engine.url.URL(
        drivername=driver_name,
        username=db_user,
        password=db_password,
        database=db_name,
        query=query_string,
      ),
      pool_size=5,
      max_overflow=2,
      pool_timeout=30,
      pool_recycle=1800
    )
    try:
        with db.connect() as conn:
            conn.execute(stmt)
    except Exception as e:
        return 'Error: {}'.format(str(e))
    return 'ok'

我主要是通过以下教程获得的:https://codelabs.developers.google.com/codelabs/connecting-to-cloud-sql-with-cloud-functions#0。我也在使用教程中使用的 Python 3.7。 SQLAlchemy 将其描述为不一定在程序员的控制下。 对于上下文,正在连接的帐户具有 SQL Cloud Admin 角色,并且启用了 Cloud SQL Admin API。在此先感谢您的帮助!

PS:我确实找到了这个答案: 但不知道在哪里可以找到带有 SQL 的防火墙设置。我没有在 SQL > 连接/概述或防火墙中找到它们。

好的,我明白了!在 Edit Function > Runtime, Build and Connection Settings 中,转到 Connection Settings 并确保启用“Only route requests to private IPs through the VPC connector”。 VPC 连接器需要不同的授权。

此外,显然我需要我的 TABLE 名称,而不是我的数据库名称作为变量 DB_NAME。感谢@guillaume blaquiere 的协助!