0
votes

I have a flask server which I want to deploy on Google Cloud Platform. The code uses MySQLdb library to connect with local MySQL instance in the following manner:

@app.route('/show_table', methods=['POST'])
def login():
    db = MySQLdb.connect("localhost", "root", "", "db_name")
    cursor = db.cursor()
    query = "select * from table_name;"
    cursor.execute(query)
    res = cursor.fetchall()
    return res, 200

But instead of local MySQL instance, I want to connect this code to Cloud SQL so that it reads data from the cloud. What changes should I make to this code? I have currently created a project in Google Cloud Platform and a Cloud SQL instance inside this project. I have also created the required tables inside this instance by following this tutorial.

1

1 Answers

2
votes

You shouldn't have to change your code too much, it just depends on how you're going to connect to the database. The Google documentation has step by step information on how to connect to Cloud SQL from an external application.

Since you're not using Java or GO, there's two options:

  1. Use the Cloud SQL proxy
  2. Whitelist the public IP address of your server on the Cloud SQL instance page

All the steps are in the documentation, but it basically says that if you use the proxy, you'll need to enable the Cloud SQL Admin API, install the proxy client on your local machine and authenticate it. There's a few authentication options but the recommended way is creating a credentials file from a service account using the console and passing the file as a parameter when you first start the proxy. Once you've got the proxy running the documentation has examples on how to connect using either TCP or UNIX sockets. With TCP you'll be using the proxy as localhost so you won't have to change your code. Using UNIX sockets you'll use the instance connection name which you'll find in your instance details on the GCP console. MySQLdb supports both.

With the second option you need to allow access to your Cloud SQL instance from a specific IP address range. Go to the connections tab in your Cloud SQL instance details page and add the IP address (using CIDR notation) you want to use to connect to your database. Once it's whitelisted then you can use the Public IP of your Cloud SQL instance, which you'll find in instance details, in place of localhost to connect to your database.