Google Cloud Function with Google Cloud SQL:Python SQLalchemy 引擎工作,但连接失败

Google Cloud Function with Google Cloud SQL: Python SQLalchemy engine works, but connection fails

我有一个简单的测试脚本来确保我可以连接到 read/write 使用 GCF 到 Google 云 SQL 实例。

def update_db(request):

    import sqlalchemy

    # connect to GCP SQL db
    user = 'root'
    pw = 'XXX'
    conn_name = 'hb-project-319121:us-east4:hb-data'
    db_name = 'Homebase'

    url = 'mysql+pymysql://{}:{}@/{}?unix_socket=/cloudsql/{}'.format(user,pw,db_name,conn_name)
    engine = sqlalchemy.create_engine(url,pool_size=1,max_overflow=0)

    # Returns
    return f'Success'

这是成功的,但是当我尝试添加连接时:

conn = engine.connect()

我收到以下错误:

pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'cloudsqlproxy~' (using password: YES)")

似乎很奇怪,可以创建引擎但无法建立连接?值得注意的是任何类型的 execute 使用引擎,例如engine.execute('select * from table limit 3')也会导致上面的错误。

如有任何想法,我们将不胜感激。感谢您的宝贵时间

干杯, 戴夫

当调用 create_engine 方法时,它会创建必要的对象,但不会实际尝试连接到数据库。

Per the SQLAlchemy documentation:

[create_engine] creates a Dialect object tailored towards [the database in the connection string], as well as a Pool object which will establish a DBAPI connection at [host]:[port] when a connection request is first received.

您从 MySQL 收到的错误消息可能是由于 special user account for the Cloud SQL Auth proxy 尚未创建。

您需要 create a user in CloudSQL (MySQL) '[USER_NAME]'@'cloudsqlproxy~%''[USER_NAME]'@'cloudsqlproxy~[IP_ADDRESS]')。