尝试从本地Google Cloud函数连接到Google Cloud MySQL数据库时,为什么会出现sqlalchemy.exc.OperationalError? [英] Why am I getting sqlalchemy.exc.OperationalError when trying to connect to Google Cloud MySQL db from a local google cloud function?
问题描述
这是我的GCP云功能"app"的要点:
Here is the gist of my GCP cloud function 'app':
main.py
import sqlalchemy
import logging
import os
from time import perf_counter
def main(data, context):
log = logging.getLogger("course_gen")
db = sqlalchemy.create_engine(
sqlalchemy.engine.url.URL(
drivername="mysql+pymysql",
username=os.environ.get("DB_USER"),
password=os.environ.get("DB_PASS"),
host="**.***.**.***", # this is actually the public IP of my cloud mysql instance
port=3306,
database="table_name"
),
pool_size=5,
max_overflow=2,
pool_timeout=30,
pool_recycle=1800
)
with db.connect() as cursor:
start_time = perf_counter()
if __name__ == '__main__':
main('data', 'context')
这是我从中复制IP的Cloud MySQL实例的相应概述:
and here is the corresponding overview of my Cloud MySQL instance from which I copied the IP:
the port
kwarg was a bit confusing but from what I've inferred from posts like this, it's always 3306.
基本上,当我在本地运行云功能时,我希望它能够连接到我已配置的实时GCP MySQL实例,但是我得到的全部错误是:
Basically when I run my cloud function locally, I expect it to be able to connect to the live GCP MySQL instance I have provisioned but the full error I'm getting is:
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on (timed out)")
推荐答案
所以我在进行一些研究时实际上已经弄清楚了-基本上我必须遵循本指南:
So I actually figured this out while I was doing some research - basically I had to follow this guide:
https://cloud.google .com/sql/docs/mysql/quickstart-proxy-test#windows-64-bit
在我的个人计算机上设置基本上是某种本地运行代理的
to set up what's basically some sort of local running proxy on my personal machine
(看起来像这样)
$ ./cloud_sql_proxy -instances=********:us-east1:********=tcp:3306
2020/05/27 22:36:06 Listening on 127.0.0.1:3306 for ********:us-east1:********
2020/05/27 22:36:06 Ready for new connections
2020/05/27 22:37:05 New connection for "********:us-east1:********"
2020/05/27 22:37:05 Client closed local connection on 127.0.0.1:3306
,然后将主机设置为localhost
或127.0.0.1
,这通过代理的魔术最终最终击中了真正的云MySQL实例.瞧,没有更多错误了.
and set the host to localhost
, or 127.0.0.1
, which through the magic of proxies eventually ends up hitting the real cloud MySQL instance. Voila no more errors.
这篇关于尝试从本地Google Cloud函数连接到Google Cloud MySQL数据库时,为什么会出现sqlalchemy.exc.OperationalError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!