如何将 MySQLdb 代码连接到 google 云 SQL?

How to connect MySQLdb code to google cloud SQL?

我有一个要部署在 Google 云平台上的烧瓶服务器。该代码使用 MySQLdb 库以下列方式连接本地 MySQL 实例:

@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

但是我想将此代码连接到云端 SQL,而不是本地 MySQL 实例,以便它从云端读取数据。我应该对此代码进行哪些更改?我目前在 Google Cloud Platform 中创建了一个项目,并在该项目中创建了一个 Cloud SQL 实例。我还通过以下方式在此实例中创建了所需的表 this教程。

您不必过多更改代码,这仅取决于您将如何连接到数据库。 Google documentation 包含有关如何从外部应用程序连接到云 SQL 的分步信息。

由于您没有使用 Java 或 GO,因此有两个选择:

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

所有步骤都在文档中,但它基本上说如果您使用代理,则需要启用 Cloud SQL Admin API,在您的计算机上安装代理客户端本地机器并对其进行身份验证。有一些 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 使用 TCP 或 UNIX 套接字。使用 TCP,您将使用代理作为本地主机,因此您不必更改代码。使用 UNIX 套接字,您将使用实例连接名称,您可以在 GCP 控制台的实例详细信息中找到该名称。我的SQLdb 支持两者。

对于 second option,您需要允许从特定 IP 地址范围访问您的 Cloud SQL 实例。转到 Cloud SQL 实例详细信息页面中的连接选项卡,并添加要用于连接到数据库的 IP 地址(使用 CIDR 表示法)。一旦它被列入白名单,您就可以使用您的云 SQL 实例的 Public IP,您可以在实例详细信息中找到它,代替本地主机连接到您的数据库。