使用将云函数连接到云SQL的示例代码,我成功地创建了一个输出略有不同的新函数。它运行了一段时间。现在,由于对代码没有任何更改,我收到一个操作错误:(2003,"无法连接到'本地主机'上的MySQL服务器([Errno 111]连接被拒绝)")。这是完整的错误:
sql-test-function-1
szzv41dltb8k
Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/pymysql/connections.py", line 570, in connect sock.connect(self.unix_socket) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 297, in run_http_function result = _function_handler.invoke_user_function(flask.request) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 199, in invoke_user_function return call_user_function(request_or_event) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 192, in call_user_function return self._user_function(request_or_event) File "/user_code/main.py", line 50, in mysql_demo mysql_conn = pymysql.connect(**mysql_config) File "/env/local/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/env/local/lib/python3.7/site-packages/pymysql/connections.py", line 327, in __init__ self.connect() File "/env/local/lib/python3.7/site-packages/pymysql/connections.py", line 629, in connect raise exc pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
我已经看到许多人们在这里和Google GitHub支持上遇到类似问题的例子,并且已经尝试了他们所有的解决方案(启用Cloud SQL Admin API,实现此Stackoverflow问题中的答案等),但我不断收到相同的错误。我尝试重新启动SQL实例,并在Chrome隐身窗口中使用相同的代码创建新函数,以避免缓存问题:相同的错误。
这是我的云函数代码:
from os import getenv
import pymysql
from pymysql.err import OperationalError
# TODO(developer): specify SQL connection details
CONNECTION_NAME = getenv(
'INSTANCE_CONNECTION_NAME',
'la-cloud-functions:us-central1:cf-sql-1')
DB_USER = getenv('MYSQL_USER', 'root')
DB_PASSWORD = getenv('MYSQL_PASSWORD', 'root')
DB_NAME = getenv('MYSQL_DATABASE', 'gallery')
mysql_config = {
'user': DB_USER,
'password': DB_PASSWORD,
'db': DB_NAME,
'charset': 'utf8mb4',
'cursorclass': pymysql.cursors.DictCursor,
'autocommit': True
}
# Create SQL connection globally to enable reuse
# PyMySQL does not include support for connection pooling
mysql_conn = None
def __get_cursor():
"""
Helper function to get a cursor
PyMySQL does NOT automatically reconnect,
so we must reconnect explicitly using ping()
"""
try:
return mysql_conn.cursor()
except OperationalError:
mysql_conn.ping(reconnect=True)
return mysql_conn.cursor()
def mysql_demo(request):
global mysql_conn
# Initialize connections lazily, in case SQL access isn't needed for this
# GCF instance. Doing so minimizes the number of active SQL connections,
# which helps keep your GCF instances under SQL connection limits.
if not mysql_conn:
try:
mysql_conn = pymysql.connect(**mysql_config)
except OperationalError:
# If production settings fail, use local development ones
mysql_config['unix_socket'] = f'/cloudsql/{CONNECTION_NAME}'
mysql_conn = pymysql.connect(**mysql_config)
# Remember to close SQL resources declared while running this function.
# Keep any declared in global scope (e.g. mysql_conn) for later reuse.
with __get_cursor() as cursor:
cursor.execute('SELECT * from albums')
row = cursor.fetchone()
while row is not None:
print(row)
row = cursor.fetchone()
如果有人有任何其他建议,我会很高兴。
蒂亚 - 乔
我通过在另一个项目中重新创建函数来解决这个问题。我不确定为什么 Cloud SQL 实例断开连接并且无法连接,但是一旦我重新建立连接,我就能够成功地重新应用函数中的代码。云功能到云SQL连接仍处于正式测试阶段,因此它可能只是一个暂时的故障。