使用云MySQL授权的谷歌云功能失败([Erno 111]连接被拒绝)



我正试图通过谷歌云函数连接到我的谷歌云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云管理员角色,并且启用了云SQL管理员API。提前感谢您的帮助!

PS:我确实找到了这个答案:使用Python和SQLAlchemy从谷歌云功能连接到云SQL,但不知道在哪里可以找到SQL防火墙的设置。我在SQL中没有找到它们>连接/概述或防火墙。

好吧,我想明白了!在编辑功能>运行时、构建和连接设置,前往连接设置并确保";仅通过VPC连接器将请求路由到私有IP";已启用。VPC连接器需要不同的授权。

此外,显然我需要我的TABLE名称,而不是作为变量DB_name的DATABASE名称。感谢@guillaume blaquiere的帮助!

相关内容

最新更新