Why am I getting sqlalchemy.exc.OperationalError when trying to connect to Google Cloud MySQL db from a local google cloud function?

半世苍凉 提交于 2020-06-17 02:51:18

问题


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')

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.

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)")

回答1:


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

(looks like this)

$ ./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

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.



来源:https://stackoverflow.com/questions/62056480/why-am-i-getting-sqlalchemy-exc-operationalerror-when-trying-to-connect-to-googl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!