Beginner Beginner - 3 years ago 184
Python Question

Python: Unable to connect to the Cloud SQL from App Engine: OperationalError: (1045)

I am trying to connect to the Cloud SQL from App Engine using example code:
https://cloud.google.com/appengine/docs/standard/python/cloud-sql/
https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/standard/cloudsql

Code:

def connect_to_cloudsql():
# When deployed to App Engine, the `SERVER_SOFTWARE` environment variable
# will be set to 'Google App Engine/version'.
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
# Connect using the unix socket located at
# /cloudsql/cloudsql-connection-name.
cloudsql_unix_socket = os.path.join(
'/cloudsql', CLOUDSQL_CONNECTION_NAME)

db = MySQLdb.connect(
unix_socket=cloudsql_unix_socket,
user=CLOUDSQL_USER,
passwd=CLOUDSQL_PASSWORD)

# If the unix socket is unavailable, then try to connect using TCP. This
# will work if you're running a local MySQL server or using the Cloud SQL
# proxy, for example:
#
# $ cloud_sql_proxy -instances=your-connection-name=tcp:3306
#
else:
db = MySQLdb.connect(
host='127.0.0.1', user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD)

return db


I have edited app.yaml file:

env_variables:
CLOUDSQL_CONNECTION_NAME: my-connection-name
CLOUDSQL_USER: root
CLOUDSQL_PASSWORD: my-cloudsql-user-password


In app.yaml, when I give env_variables are for the local SQL client, the code works.

But, when I give env_variables are for cloud SQL, I am get error:
OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
for this line:

db = MySQLdb.connect(host='127.0.0.1', user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD)


I think for cloud SDK,
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/')
should be True.
So, when I force if to be True:
if True:
, I get same error:
OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
for line:
db = MySQLdb.connect(unix_socket=cloudsql_unix_socket, user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD)
.

The 'root@localhost' use have all the privileges:
enter image description here
enter image description here

Please help to connect to the Cloud SQL from App Engine

Answer Source

You are connecting to Cloud SQL from your local environment, so you need to start the Cloud SQL Proxy. Depending on your language and environment, you can start the proxy using either TCP sockets or Unix sockets.

cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:3306

Install the Cloud SQL Proxy https://dl.google.com/cloudsql/cloud_sql_proxy_x64.exe (renaming it to cloud_sql_proxy.exe)

Also, you need to login for application default creadentials:

gcloud auth application-default login
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download