Home > Mobile >  App Engine connection to cloud-sql issues
App Engine connection to cloud-sql issues

Time:05-10

I'm using flask_mysqldb (https://github.com/alexferl/flask-mysqldb/blob/master/flask_mysqldb/__init__.py) to connect to cloud sql from app engine.

I'm passing the following params to it:

MYSQL_HOST = "PUBLIC IP of the cloud sql instance"
MYSQL_UNIX_SOCKET = '/cloudsql/<project_id>:<region>:<instance name>'
MYSQL_USER = 'user'
MYSQL_PASSWORD = 'pword'

But I'm getting an error message when trying to connect from app engine:

MySQLdb._exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'PUBLIC_IP_ADDRESS' (110)")

When I allow all connections to the cloud sql instance (i.e. allow 0.0.0.0/0 as allowed network), then app engine succeeds and is able to connect.

The app engine instance is in the same project as the cloud sql instance, and the app engine service account has the right permissions.

Any ideas what the issue is ? thanks

CodePudding user response:

This error is being caused by the fact that you are setting both MYSQL_HOST and MYSQL_UNIX_SOCKET in your example. Setting MYSQL_HOST tells flask-mysqldb to connect via a TCP connection, while setting MYSQL_UNIX_SOCKET tells it to connect via Unix sockets. These are conflicting and thus causing the error you are seeing.

Don't set MYSQL_HOST, remove it from your code and everything should work fine:

from flask import Flask
from flask_mysqldb import MySQL

app = Flask(__name__)

# Required
app.config["MYSQL_USER"] = <YOUR_DB_USER>
app.config["MYSQL_PASSWORD"] = <YOUR_DB_PASSWORD>
app.config["MYSQL_DB"] = <YOUR_DB_NAME>
app.config["MYSQL_UNIX_SOCKET"] = '/cloudsql/<PROJECT_ID>:<REGION>:<INSTANCE_NAME>'
# Extra configs, optional:
app.config["MYSQL_CURSORCLASS"] = "DictCursor"

mysql = MySQL(app)

@app.route("/")
def users():
    cur = mysql.connection.cursor()
    cur.execute("""SELECT user, host FROM mysql.user""")
    rv = cur.fetchall()
    return str(rv)

if __name__ == "__main__":
    app.run(debug=True)

With the above change you should no longer have to allow 0.0.0.0/0 as an allowed network.

  • Related