[英]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.我有一个简单的测试脚本来确保我可以使用 GCF 连接和读/写到 Google Cloud 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'
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.值得注意的是,使用引擎的任何类型的
execute
,例如engine.execute('select * from table limit 3')
也会导致上述错误。
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.当
create_engine
方法被调用时,它会创建必要的对象,但实际上并不尝试连接到数据库。
Per the SQLAlchemy documentation :根据 SQLAlchemy 文档:
[create_engine] creates a
Dialect
object tailored towards [the database in the connection string], as well as aPool
object which will establish a DBAPI connection at [host]:[port] when a connection request is first received.[create_engine] 创建一个针对 [连接字符串中的数据库] 定制的
Dialect
对象,以及一个Pool
对象,该对象将在首次收到连接请求时在 [host]:[port] 建立 DBAPI 连接。
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.您从 MySQL 收到的错误消息可能是因为尚未创建Cloud SQL Auth 代理的特殊用户帐户。
You need to create a user in CloudSQL (MySQL) ( '[USER_NAME]'@'cloudsqlproxy~%'
or '[USER_NAME]'@'cloudsqlproxy~[IP_ADDRESS]'
).您需要在 CloudSQL (MySQL) 中创建一个用户(
'[USER_NAME]'@'cloudsqlproxy~%'
或'[USER_NAME]'@'cloudsqlproxy~[IP_ADDRESS]'
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.