【发布时间】:2021-07-16 16:39:19
【问题描述】:
我正在尝试通过 Google Cloud Function 连接到我的 Google Cloud 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:我确实找到了这个答案:Connecting to Cloud SQL from Google Cloud Function using Python and SQLAlchemy,但不知道在哪里可以找到带有 SQL 的防火墙的设置。我没有在 SQL > Connection / Overview 或 Firewall 中找到它们。
【问题讨论】:
-
您的 Cloud SQL 实例是否有公共 IP?什么是数据库引擎和版本?你如何部署你的云功能?你能分享你使用的参数吗?
-
是的,我同时启用了公共和私有 IP,但我不确定是否/我必须为函数的 IP 输入什么。我正在使用 MySQL 8.0。我只需单击“部署”即可部署。你指的是哪些参数?编辑:我想我进去了!连接是通过我的 VPC 强制连接的,但是当我关闭它时,我收到消息“未知数据库 'supermarkt-database'”(尽管这是数据库的名称)
标签: mysql python-3.x google-cloud-platform google-cloud-functions google-cloud-sql