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:


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(

db = MySQLdb.connect(

# 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
db = MySQLdb.connect(

return db

I have edited app.yaml file:

CLOUDSQL_CONNECTION_NAME: my-connection-name
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='', 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 (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