简体   繁体   中英

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

I have a simple test script to ensure I can connect to and read/write using GCF to Google Cloud SQL instance.

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'

This is successful but when I try to add a connection:

conn = engine.connect()

I get the following error:

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

Seems odd that engine can be created but no connection can be made to it? Worth noting that any kind of execute using the engine, eg engine.execute('select * from table limit 3') will also lead to the error above.

Any thoughts are appreciated. Thanks for your time

Cheers, Dave

When the create_engine method is called, it creates the necessary objects, but does not actually attempt to connect to the database.

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.

The error message you receive from MySQL is likely due to the fact that the special user account for the Cloud SQL Auth proxy has not yet been created.

You need to create a user in CloudSQL (MySQL) ( '[USER_NAME]'@'cloudsqlproxy~%' or '[USER_NAME]'@'cloudsqlproxy~[IP_ADDRESS]' ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM