【发布时间】:2019-05-26 11:37:59
【问题描述】:
使用将云函数连接到 Cloud SQL 的示例代码,我成功创建了一个输出略有不同的新函数。它运行了一段时间。现在,对代码没有任何更改,我得到一个 OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection denied)")。这是完整的错误:
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,在this Stackoverflow question 中实现答案等),但我不断得到同样的错误。我尝试重新启动 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()
如果有人有任何其他建议,我会很高兴。
TIA - 乔
【问题讨论】:
标签: google-cloud-platform google-cloud-functions google-cloud-sql